具有 jsonp 内容类型的 jQuery.ajax 请求后的解析器错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5359224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parsererror after jQuery.ajax request with jsonp content type
提问by Thomas
I am using jQuery Version 1.5.1 to do the following ajax call:
我正在使用 jQuery 1.5.1 版来执行以下 ajax 调用:
$.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); }
});
The server responds with a valid json object:
服务器使用有效的 json 对象进行响应:
{
"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
Why does this happen?
为什么会发生这种情况?
I am using no additional libraries to jQuery.
我没有对 jQuery 使用额外的库。
EDIT:
编辑:
If I try to make the ajax call with "json" as dataType instead of "jsonp", the server responds with an empty string.
如果我尝试使用“json”作为数据类型而不是“jsonp”进行 ajax 调用,服务器会以空字符串响应。
采纳答案by Evan Trimboli
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.
JSONP 要求将响应包装在某种回调函数中,因为它的工作原理是将脚本标记注入文档,作为从另一个域加载数据的机制。
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
is dependent on the resource you're calling, it's common for the parameter to be callback
though.
callback
取决于您正在调用的资源,但参数很常见callback
。
someFn
is then used to process the returned data from the server, so the server should respond with:
someFn
然后用于处理从服务器返回的数据,因此服务器应响应:
someFn({theData: 'here'});
The someFn is passed as part of the request, so the server needs to read it and wrap the data appropriately.
someFn 作为请求的一部分传递,因此服务器需要读取它并适当地包装数据。
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
这一切都假设您从另一个域中获取内容。如果是这样,您将受到同源政策的限制:http: //en.wikipedia.org/wiki/Same_origin_policy
回答by Bryan
After upgrading to Jquery 1.5 and attempting to make a call across domains I had the same problem. Eventually I found the $.getJSON worked. Specifically,
升级到 Jquery 1.5 并尝试跨域进行调用后,我遇到了同样的问题。最终我发现 $.getJSON 有效。具体来说,
$.getJSON(url,
function(data){
yourFunction(data);
return false;
});
The URL I used was like this:
我使用的网址是这样的:
var url = WEB_SERVER_URL;
url = url + "&a=" + lat;
url = url + "&b=" + lng; ....
url = url + "&jsoncallback=?";
In the server, which is running on another server and I have control of this code was added:
在另一台服务器上运行且我可以控制的服务器中添加了以下代码:
PrintWriter writer = response.getWriter();
String jsonString = json.toString(JSON_SPACING);
String callback = request.getParameter("jsoncallback");
// if callback in URL and is not just the "?" (e.g. from localhost)
if (callback != null && callback.length() > 1)
{
writer.write(callback + "(" + jsonString + ");");
}
else
{
writer.write(jsonString);
}
(The json object is an instance of JSONObject, the code can be found here http://www.json.org/java/)
(json 对象是 JSONObject 的一个实例,代码可以在这里找到http://www.json.org/java/)
回答by Rohit
when you are using jsonp as datatype (making cross domain request) Jquery generate random function and append is to requested url as a querystring named callback (callback=?), you need to append response json data as a parameter of this function as given below -
当您使用 jsonp 作为数据类型(进行跨域请求)Jquery 生成随机函数并附加到请求的 url 作为名为回调的查询字符串(回调=?)时,您需要附加响应 json 数据作为此函数的参数,如下所示——
url : http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request
url call by ajax :
http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request&callback=jQuery1510993527567155793_137593181353
Response data should look like this :
响应数据应如下所示:
string callback = context.Request.QueryString["callback"];
if (!string.IsNullOrEmpty(callback))
context.Response.Write(string.Format("{0}({1});", callback, jc.Serialize(outputData)));
else
context.Response.Write(jc.Serialize(outputData));
Read more about :parsererror after jquery.ajax request with jsonp content type
阅读更多关于:jsonp 内容类型的 jquery.ajax 请求之后的解析器错误
回答by sdepold
there is one little mistake :) You have to request .js and not .json.
有一个小错误:) 您必须请求 .js 而不是 .json。
$.ajax({
dataType: 'jsonp',
data: { api_key : apiKey },
url: "http://de.dawanda.com/api/v1/" + resource + ".js",
success: function(data) { console.log(data); },
error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
});
Ah and did you notice, that there is a client for the api ? https://github.com/dawanda/dawanda-api-client-js
啊,你有没有注意到,api 有一个客户端?https://github.com/dawanda/dawanda-api-client-js
回答by William
Ensure that the service you are calling has the ability to return data in JsonP format.
确保您调用的服务能够以 JsonP 格式返回数据。
If you are using asp.net webapi, you can use WebApiContrib.Formatting.Jsonp, it's open source.
如果你使用的是 asp.net webapi,你可以使用 WebApiContrib.Formatting.Jsonp,它是开源的。
Ensure that you have a line like below in WebApiConfig.Register.
确保您在 WebApiConfig.Register 中有如下一行。
config.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter(), "callback"));
config.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter(), "callback"));
I was pulling my hair over this. Hope this helps someone.
我正在拉我的头发。希望这可以帮助某人。
回答by jAndy
You really shouldn't specify jsonphere. Just use jsonbecause you're just receiving a JSON string. json(json with padding) expects a javascript function execute. In that case you need to specify a "callback=" within your querystring. I guess that is.the reason why jQuery can't handle this aswell, there is a property with the name callback.
你真的不应该在这里指定jsonp。只需使用json因为您只是收到一个 JSON 字符串。json(带填充的 json)需要一个 javascript 函数执行。在这种情况下,您需要在查询字符串中指定一个“callback=”。我想这就是 jQuery 无法处理这个的原因,有一个名为回调的属性。
回答by Adam
Try reading the response into an object using $.parseJSON:
尝试使用 $.parseJSON 将响应读入一个对象:
success: function(data) {
var json = $.parseJSON(data);
}
回答by Parveen Verma
The same problem I was getting until I have not appended parameter "callback=?" or "c=?" in url.
在我没有附加参数“callback=?”之前,我遇到了同样的问题 或“c=?” 在网址中。
Like : "http://de.dawanda.com/api/v1/" + resource + ".json&c=?"
May solve your problem. It worked for me.
比如:“ http://de.dawanda.com/api/v1/”+资源+“.json&c=?”
可以解决你的问题。它对我有用。
回答by mAsT3RpEE
Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp (But might in the future):
并非所有服务器都支持 jsonp。它要求服务器在其结果中设置回调函数。我使用它从返回纯 json 但不支持 jsonp 的站点获取 json 响应(但可能在未来):
function AjaxFeed(){
return $.ajax({
url: 'http://somesite.com/somejsonfile.php',
data: {something: true},
dataType: 'jsonp',
/* Very important */
contentType: 'application/json',
});
}
function GetData()
AjaxFeed()
/* Everything worked okay. Hooray */
.done(function(data){
return data;
})
/* Okay jQuery is stupid manually fix things */
.fail(function(jqXHR) {
/* Build HTML and update */
var data = jQuery.parseJSON(jqXHR.responseText);
return data;
});
}