[英]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)
的形式,其中, data
將是“JSON”(或者更通常,一個JavaScript的文本,這可能不是完全一樣的東西)。 你打算在script
標簽的src
(jQuery為你做的)中使用JSON-P URL來繞過同源策略 ,該策略防止ajax請求從源自它們的文檔之外的原點請求數據(除非服務器支持CORS ,您的瀏覽器也支持)。
最后我找到了解決方案。 首先,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);
}
});
});
並且工作得很好
加布里埃爾
如果服務器不支持cross domain
請求,您可以:
json
,並且 在PHP中你可以這樣做
proxy.php包含以下代碼
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
你像這樣對你的代理做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>
經過試驗和測試我得到了json回復...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.