[英]ajax make responseText to be an object
我需要获取ajax答案作为DOM对象。
这是我的代码:
$.ajax(URL, {
async: false,
complete: function(e){
code = $(e.responseText);
alert( code.find('body').length );
}
});
因此,我需要将响应作为对象,然后在其中进行选择。
但是在先前的示例中,我的Firebug返回了:
Object[<TextNode textContent="\n\n \n ">, title, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">
例如,此代码可以正常工作:
$.get(URL, function(e){
var code = $(e);
alert( code.find('body').length );
});
但是我需要发出一个异步请求,因此$ .get不是一个选项(否则我无法找到解决方案)。
感谢您的指教!
您的ajax代码不正确,应该是这样,您可以在成功回调中获取响应:
$.ajax({
url:URL,
type : "get",
dataType: "html", // expected output from the requested url
success: function(e){
code = $(e.responseText); // or try with $(e) only
alert( code.find('body').length );
},
error: function(err){
alert(err.responseText);
}
});
我目前发现的唯一解决方案是将返回的数据制成html,然后便可以对其进行操作。 我的工作示例是:
$.ajax({
url: URL,
async: false,
type : "get",
dataType: "html",
success: function(data){
var response = $('<html/>').html(data);
alert(response.find('#ELEM').length);
}
});
因此,如您所见-我将响应数据制成HTML,这有助于我使用.find()
和其他有用的东西。
希望此解决方案会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.