我正在使用 jQuery 制作简单的自动建议(自动完成器)插件。不幸的是我必须使用jsonp。没关系,它可以工作,但是当我中止请求时,它会抛出错误。
Uncaught TypeError: Property 'jQuery171036404498340561986_1330693563756' of object [object Window] is not a function
有代码
if(xhr) {xhr.abort()};
xhr = $.ajax({
url: "someurl/getmedata",
type: 'get',
dataType: 'jsonp',
data: {q: "query"},
success: function(results) {},
error: function() {}
})
使用 json、xml 或其他请求的经典方式效果很好。
有什么建议吗?
最佳答案
JSONP
不使用XMLHTTPRequest
但实际上创建了一个 <script>
文档中的标记以便能够发出跨域请求。
您根本无法中止 JSONP 请求。
$.ajax()中有说明文档:
Some types of Ajax requests, such as JSONP and cross-domain GET requests, do not use XHR; in those cases the XMLHttpRequest and textStatus parameters passed to the callback are undefined.
对于 jQuery 1.5+,之前是从 $.ajax() 返回 XHR 对象,现在它返回一个封装了 XHR 对象的超集 jqXHR 对象。
When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.
因此它返回一个对象,但某些功能实际上不可用,例如 .abort()。
<小时/>插件 jQuery-JSONP 似乎提供了手动中止 JSONP 请求的可能性。我自己没有使用过,但值得一试。
关于jquery - 中止 jQuery JSONP 请求将引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533848/