jQuery 1.5.2 显示空响应的 [object XMLDocument]
我有一个 Url,从中我可以获取一个字符串
如果响应字符串包含某些内容,一切都会顺利,但是(上帝禁止!)如果结果是像“”这样的空字符串,jQuery 1.5.2 会将其显示为 [object XMLDocument]
请遵循代码:
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
{
//do something here!
}
else
{
console.log(data.toString());
// [object XMLDocument] will be printed in console.
}
});
也许我应该提到它曾经在 jQuery 1.4.4 上完美工作 有什么想法吗?
问候 :)
I have a Url from which I can get a string
If the response string contains something, everything goes well, but (god forbid!) if the result would be an empty string like "" jQuery 1.5.2 will display it as [object XMLDocument]
follow the codes plz :
$.post('/Applicant/RequestedJob/IsThereActivePeriod',{},
function(data){
if(data == '' )
{
//do something here!
}
else
{
console.log(data.toString());
// [object XMLDocument] will be printed in console.
}
});
Perhaps I should mention that it used to work perfectly on jQuery 1.4.4
any idea?
Regards :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在 ajax 调用中设置响应的预期数据类型,如下所示:
如果没有此设置,jQuery 会尝试根据 对此:
由于没有返回内容,它显然是在猜测 XML。通过将“html”作为数据类型传递,您可以强制 jQuery 将响应解释为 HTML,并以纯文本形式存储结果。
根据一些评论,适当的内容类型标头应该允许 jQuery 推断您的空字符串是 HTML,从而无需在 ajax 调用中显式设置预期的 dataType 即可获得相同的结果。
您得到
[object XMLDocument]
的原因是因为data
是一个XML 文档对象,并且正在调用它的toString()。You should set the expected dataType of the response in your ajax call, like this:
Without this, jQuery tries to infer the response type, according to this:
With no returned content, it's apparently guessing XML. By passing it 'html' as the dataType, you force jQuery to interpret the response as HTML, and store the result in plain text.
As per some of the comments, an appropriate content-type header should allow jQuery to infer that your empty string is HTML, achieving the same result without setting the expected dataType explicitly in the ajax call.
The reason you get
[object XMLDocument]
is becausedata
is an XML document object, and its toString() is being called.