jQuery.ajax()parsererror
当我尝试从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); } });
我得到: parsererror; 200; undefined; jquery162******************** was not called
parsererror; 200; undefined; jquery162******************** was not called
但是使用http://search.twitter.com/search.json?q=beethoven&callback=?&count=5中的JSON工作正常。 两者都是有效的JSON格式。 那么这个错误是什么?
[UPDATE]
@ 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:
[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; } }
这是因为你告诉jQuery你期待JSON-P ,而不是JSON 。 但回报是JSON。 JSON-P的名字非常错误,以一种不会导致混淆的方式命名。 这是一种通过script
标记将数据传递给函数的约定 。 相比之下,JSON是一种数据格式。
JSON示例:
{"foo": "bar"}
JSON-P的示例:
yourCallback({"foo": "bar"});
JSON-P起作用,因为JSON是JavaScript文字表示法的子集。 JSON-P只不过是一个承诺,如果你告诉服务你正在调用要callback
函数名称(通常通过在请求中放置一个callback
参数),响应将采用functionname(data)
的forms, data
将是“JSON”(或更常见的是,JavaScript文字,可能不是完全相同的东西)。 你打算在script
标签的src
(jQuery为你做的)中使用JSON-P URL,以绕过同源策略 ,该策略防止ajax请求从源自它们的文档之外的原点请求数据(除非服务器支持CORS ,您的浏览器也支持)。
如果服务器不支持cross domain
请求,您可以:
- 创建服务器端代理
- 向您的代理执行ajax请求,然后从服务中获取
json
,并且 - 返回响应,然后你可以操纵它…
在PHP中你可以这样做
proxy.php包含以下代码
并且像这样对你的代理执行ajax请求
经过试验和测试我得到了json回复…
最后我找到了解决方案。 首先,web服务或页面中的web方法对我不起作用,它总是返回xml,在本地工作正常但在像godaddy这样的服务提供者中却没有。
我的解决方案是在.net中创建一个.ahsx
,一个处理程序,并使用传递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; } }
这是与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); } }); });
并且工作得很好
加布里埃尔