当我尝试从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
但是使用来自http://search.twitter.com/search.json?q=beethoven&callback=?&count=5的JSON可以正常工作。两者都是有效的JSON格式。那么这个错误是关于什么的呢?
[更新]
@ 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
在请求中放置参数),则响应将采用的形式functionname(data)
,其中data
将是“ JSON ”(或更常见的是JavaScript文字,这可能不太一样)。您应该在script
标记的JSON中使用JSON-P URL src
(jQuery为您执行此操作),以避开Same Origin Policy,该策略可防止ajax请求从其原始文档以外的其他来源请求数据(除非服务器支持)CORS和您的浏览器也可以)。
如果服务器不支持该cross domain
请求,则可以:
- 创建服务器端代理
- 向您的代理发出ajax请求,代理将依次
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响应...
最后,我找到了解决方案。首先,Web服务或页面中的Web方法对我不起作用,它始终返回xml,在本地工作正常,但在Godaddy这样的服务提供商中却无效。
我的解决方案是.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;
}
}
这是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);
}
});
});
并完美地工作
加布里埃尔
文章标签:javascript , jquery , json , parse-error
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!