Javascript jQuery.ajax() 解析器错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6643838/
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
jQuery.ajax() parsererror
提问by Stack Stack
when i try to get JSON from http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=jsonwith:
当我尝试从http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json获取 JSON时:
(jQuery 1.6.2)
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (result) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
I get: parsererror; 200; undefined; jquery162******************** was not called
我得到: parsererror; 200; undefined; jquery162******************** was not called
but with the JSON from http://search.twitter.com/search.json?q=beethoven&callback=?&count=5works fine. Both are valid JSON formats. So what is this error about?
但是来自http://search.twitter.com/search.json?q=beethoven&callback=?&count=5的 JSON工作正常。两者都是有效的 JSON 格式。那么这个错误是关于什么的呢?
[UPDATE]
[更新]
@3ngima, i have implemented this in asp.net, it works fine:
@3ngima,我已经在 asp.net 中实现了它,它工作正常:
$.ajax({
type: "POST",
url: "WebService.asmx/GetTestData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
WebService.asmx:
WebService.asmx:
[WebMethod]
public string GetTestData()
{
try
{
var req = System.Net.HttpWebRequest.Create("http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json");
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new System.IO.StreamReader(stream))
return reader.ReadToEnd();
}
catch (Exception) { return null; }
}
回答by T.J. Crowder
It's because you're telling jQuery that you're expecting JSON-P, not JSON, back. But the return is JSON. JSON-P is horribly mis-named, named in a way that causes no end of confusion. It's a conventionfor conveying data to a function via a script
tag. In contrast, JSON is a data format.
这是因为您告诉 jQuery 您期望返回JSON-P而不是JSON。但返回的是 JSON。JSON-P 被错误地命名了,以一种不会引起混乱的方式命名。这是通过标签将数据传送到函数的约定script
。相比之下,JSON 是一种数据格式。
Example of JSON:
JSON 示例:
{"foo": "bar"}
Example of JSON-P:
JSON-P 示例:
yourCallback({"foo": "bar"});
JSON-P works because JSON is a subset of JavaScript literal notation. JSON-P is nothing more than a promise that if you tell the service you're calling what function name to call back (usually by putting a callback
parameter in the request), the response will be in the form of functionname(data)
, where data
will be "JSON" (or more usually, a JavaScript literal, which may not be the quitethe same thing). You're meant to use a JSON-P URL in a script
tag's src
(which jQuery does for you), to get around the Same Origin Policywhich prevents ajax requests from requesting data from origins other than the document they originate in (unless the server supports CORSand your browser does as well).
JSON-P 之所以有效,是因为 JSON 是 JavaScript 文字符号的一个子集。JSON-P 只不过是一个承诺,如果你告诉服务你正在调用什么函数名称来回调(通常通过callback
在请求中放置一个参数),响应将采用 的形式functionname(data)
,其中data
将是“JSON "(或者更常见的是 JavaScript 文字,这可能不是完全一样的东西)。您打算在script
标签src
(jQuery 为您做的)中使用 JSON-P URL ,以绕过同源策略,该策略阻止 ajax 请求从它们起源的文档以外的其他来源请求数据(除非服务器支持CORS和您的浏览器也是如此)。
回答by Rafay
in case the server does not support the cross domain
request you can:
如果服务器不支持该cross domain
请求,您可以:
- create a server side proxy
- do ajax request to your proxy which in turn will get
json
from the service, and - return the response and then you can manipulate it ...
- 创建服务器端代理
- 向您的代理发出 ajax 请求,代理
json
将从服务中获取,并且 - 返回响应,然后您可以对其进行操作...
in php you can do it like this
在 php 中你可以这样做
proxy.php contains the following code
proxy.php 包含以下代码
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and you do the ajax request to you proxy like this
你像这样向你的代理发出ajax请求
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
alert("abt to do ajax");
$.ajax({
url:'proxy.php',
type:"POST",
data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
success:function(data){
alert("success");
alert(data);
}
});
});
});
</script>
tried and tested i get the json response back...
经过尝试和测试,我得到了 json 响应......
回答by gabriel
At last i have found the solution. First of all, the webmethods in a webservice or page doesn't work for me, it always returns xml, in local works fine but in a service provider like godaddy it doesn't.
最后我找到了解决方案。首先,webservice 或页面中的 webmethods 对我不起作用,它总是返回 xml,在本地工作正常,但在像 Godaddy 这样的服务提供商中却没有。
My solution was to create an .ahsx
, a handler in .net and wrap the content with the jquery callback function that pass the jsonp, and it works .
我的解决方案是.ahsx
在 .net 中创建一个处理程序,并使用传递 jsonp 的 jquery 回调函数包装内容,并且它可以工作。
[System.Web.Script.Services.ScriptService]
public class HandlerExterno : IHttpHandler
{
string respuesta = string.Empty;
public void ProcessRequest ( HttpContext context )
{
string calls= context.Request.QueryString["callback"].ToString();
respuesta = ObtenerRespuesta();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write( calls +"("+ respuesta +")");
}
public bool IsReusable
{
get
{
return false;
}
}
[System.Web.Services.WebMethod]
private string ObtenerRespuesta ()
{
System.Web.Script.Serialization.JavaScriptSerializer j = new System.Web.Script.Serialization.JavaScriptSerializer();
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
respuesta = j.Serialize(e).ToString();
return respuesta;
}
}//class
public class Employee
{
public string Name
{
get;
set;
}
public string Company
{
get;
set;
}
public string Address
{
get;
set;
}
public string Phone
{
get;
set;
}
public string Country
{
get;
set;
}
}
And here is the call with jquery:
这是与 jquery 的调用:
$(document).ready(function () {
$.ajax({
// url: "http://www.wookmark.com/api/json",
url: 'http://www.gjgsoftware.com/handlerexterno.ashx',
dataType: "jsonp",
success: function (data) {
alert(data[0].Name);
},
error: function (data, status, errorThrown) {
$('p').html(status + ">> " + errorThrown);
}
});
});
and works perfectly
并且完美运行
Gabriel
加布里埃尔