jQuery .find() on data from .ajax() call is returning quot;[object Object]quot; instead of div(来自 .ajax() 调用的数据的 jQuery .find() 正在返回“[object Object].而不是 div)
问题描述
试图在 .ajax() 使用 .find()代码>.不幸的是,alert(result) 不返回 div#result.
这是我的代码:
$.ajax({网址:网址,缓存:假,成功:功能(响应){结果 = $(response).find("#result");警报(响应);//按预期工作(返回所有 html)警报(结果);//返回 [object 对象]}});具体回答您的问题,它似乎工作正常.您说它返回 [object Object],这就是 jQuery 使用 find("#result") 方法返回的内容.它返回一个匹配 find 查询的 jQuery 元素.
尝试获取该对象的属性,例如 result.attr("id") - 它应该返回 result.
一般来说,这个答案取决于 #result 是否是顶级元素.
如果#result是顶级元素,
<div id="结果"><span>文本</span></div><div id="其他顶级元素"></div>find() 将不起作用.相反,使用 filter():
var $result = $(response).filter('#result');如果#result不是顶级元素,
<div id="结果"><span>文本</span></div></div>find() 会起作用:
var $result = $(response).find('#result');
Trying to find div element with id="result" in returned data from .ajax() using .find(). Unfortunately, alert(result) doesn't return div#result.
Here is my code:
$.ajax({
url: url,
cache: false,
success: function(response) {
result = $(response).find("#result");
alert(response); // works as expected (returns all html)
alert(result); // returns [object Object]
}
});
解决方案 To answer your question specifically, it seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method. It returns a jQuery element that matches the find query.
Try getting an attribute of that object, like result.attr("id") - it should return result.
In general, this answer depends on whether or not #result is the top level element.
If #result is the top level element,
<!-- #result as top level element -->
<div id="result">
<span>Text</span>
</div>
<div id="other-top-level-element"></div>
find() will not work. Instead, use filter():
var $result = $(response).filter('#result');
If #result is not the top level element,
<!-- #result not as top level element -->
<div>
<div id="result">
<span>Text</span>
</div>
</div>
find() will work:
var $result = $(response).find('#result');
这篇关于来自 .ajax() 调用的数据的 jQuery .find() 正在返回“[object Object]".而不是 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:来自 .ajax() 调用的数据的 jQuery .find() 正在返回“[object Object]".而不是 div
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
