具有jsonp内容类型的jQuery.ajax请求后发生parsererror [英] parsererror after jQuery.ajax request with jsonp content type
问题描述
我正在使用jQuery 1.5.1版执行以下ajax调用:
I am using jQuery Version 1.5.1 to do the following ajax call:
$.ajax({
dataType: 'jsonp',
data: { api_key : apiKey },
url: "http://de.dawanda.com/api/v1/" + resource + ".json",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
});
服务器使用有效的json对象进行响应:
The server responds with a valid json object:
{
"response": {
"type":"category",
"entries":1,
"params":{
"format":"json",
"api_key":"c9f11509529b219766a3d301d9c988ae9f6f67fb",
"id":"406",
"callback":"jQuery15109935275333671539_1300495251986",
"_":"1300495252693"
},
"pages":1,
"result":{
"category":{
"product_count":0,
"id":406,
"restful_path":"/categories/406",
"parent_id":null,
"name":"Oberteile"
}
}
}
}
但是从不调用成功回调,而是由错误回调产生以下输出:
But the success callback is never called, instead the error callback produces this output:
jQuery15109935275333671539_1300495251986 was not called
parsererror
为什么会这样?
我没有使用jQuery的其他库.
I am using no additional libraries to jQuery.
如果我尝试使用"json"作为dataType而不是"jsonp"来进行ajax调用,则服务器将以空字符串作为响应.
If I try to make the ajax call with "json" as dataType instead of "jsonp", the server responds with an empty string.
推荐答案
JSONP要求将响应包装在某种回调函数中,因为它通过将脚本标记注入文档中来作为从另一个加载数据的机制来工作.域.
JSONP requires that the response be wrapped in some kind of callback function, because it works by injecting a script tag into the document as a mechanism to load data from another domain.
本质上,发生的是脚本标记被动态插入到文档中,如下所示:
Essentially, what happens is a script tag gets dynamically inserted into the document like so:
<script src="http://the.other.server.com/foo?callback=someFn"></script>
callback
取决于您正在调用的资源,但是参数通常为callback
.
callback
is dependent on the resource you're calling, it's common for the parameter to be callback
though.
someFn
然后用于处理从服务器返回的数据,因此服务器应以以下方式响应:
someFn
is then used to process the returned data from the server, so the server should respond with:
someFn({theData: 'here'});
someFn作为请求的一部分传递,因此服务器需要读取它并适当包装数据.
The someFn is passed as part of the request, so the server needs to read it and wrap the data appropriately.
这都是假设您要从另一个域中获取内容.如果是这样,您将受到相同的来源政策的限制: http://en.wikipedia.org/wiki /Same_origin_policy
This is all assuming you're grabbing the content from another domain. If so, you're limited by the same origin policy: http://en.wikipedia.org/wiki/Same_origin_policy
这篇关于具有jsonp内容类型的jQuery.ajax请求后发生parsererror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!