AJAX 响应文本作为 DOM?
考虑使用 jQuery 的以下函数:
function getVal() {
jQuery.get('/relative/url/', function (data) {
return data.getElementById('myInput').value;
}
}
这基本上就是我想要做的,但我不知道应该如何完成。 我知道唯一可行的方法涉及框架或innerHTML,但我无法使用它们,因为我必须等待元素准备好。唯一的方法是使用回调,并且此函数必须返回元素的值而不是其他值。 我的逻辑可能有问题,请大家指正。
Consider the following function using jQuery:
function getVal() {
jQuery.get('/relative/url/', function (data) {
return data.getElementById('myInput').value;
}
}
This is basically what I want to do, but I have no idea how it should be done.
The only methods I know would work involve frames or innerHTML which I can't use because I have to wait for the element to be ready. The only way to do that is to use a callback, and this function must return the value of the element rather than something else.
My logic is likely faulty here, so please feel free to correct me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
首先,对于当前的结构,您应该使用回调来返回值。要解析通过 AJAX 检索到的 HTML 字符串,您可以将其交给 jQuery,然后像往常一样查询它。
然后,当您调用函数
getVal
时,您需要提供回调:First of all, with your current structure you should use a callback to return the value. To parse the HTML string retrieved via AJAX, you can hand it to jQuery and then query it just as usual.
Then, when you are calling the function
getVal
, you'll need to provide a callback:不,你不能这样做......因为它是异步调用。您需要的是为您的代码提供回调以返回值
No, you could not do that.. since it is ansync call. What you need is to provide a callback to you code, to return the value
如果它是有效的 html 标记,您可以使用选择器浏览其 xml:
或者您可以只在页面中的某个虚拟元素上呈现标记,然后进行查找:
if the it's valid html markup, you can use browse its xml with the selector:
or you can just render the markup on some dummy element in your page and then do you lookup:
除非将元素添加到 dom 树中,否则您无法执行此操作。
You cannot do that unless the elements are added to dom tree.
有几个问题。首先,您不能从这样的回调中
返回
。您只需返回匿名函数本身,而不是从getVal()
方法返回。为了解决这个问题,您可以返回
jXHR
对象并应用一些魔法:我不知道
data
的结构是什么样的,但它应该以这种方式工作。如果不是,可能是因为myInput
位于顶层。在这种情况下,请将.find()
替换为.filter()
。Several problems there. First, you cannot
return
from a callback like that. You would just return to the anonymous function itself, not from thegetVal()
method.To solve that, you can return the
jXHR
object and apply some magic:I don't know how the structure from
data
looks like, but it should work that way. If not, its probably because ofmyInput
is on the top level. In that case, replace.find()
with.filter()
.哦,好吧。我明白了。我认为我没有提供足够的信息。我认为上下文无关紧要。好的,这是一个描述我的解决方案的示例。
Oh, alright. I've got it. I don't think I provided enough information. I assumed context was irrelevant. Alright, here's an example depicting my solution.