2011-05-11 100 views
0

我正在使用以下代码以JSONP格式检索数据。我需要使用它,所以如果没有数据返回,我可以标记错误。我使用的是jQuery的ajax(),但它总是返回404页成功,所以我需要在Google Code上使用jquery-jsonp jQuery插件进行错误处理。为什么我会一直收到这个JSONP feed的“未定义”错误?

我借用了jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event上的示例中的代码,但似乎无法让它与我的JSON一起工作,该JSON作为MIME类型“application/json”从其他服务器发送。

$(function(){ 
    var jsonFeed = "http://othersite.com/feed.json"; 

    $.jsonp({ 
     url: jsonFeed, 
     dataType: "jsonp", 
     timeout: 5000, 
     success: function(data, status){ 
      $.each(data.items, function(i,item){ 
       console.log("Title: " + item.title); 

       if (i == 9) return false; 
      }); 
     }, 
     error: function(XHR, textStatus, errorThrown){ 
      console.log("Error Status: " + textStatus); 
      console.log("Error Thrown: " + errorThrown); 
     } 
    }); 
}); 

这里是我的JSON的例子:

任何人都可以发现问题:

[{ “我的标题”, “标题”}]?

+1

从服务器返回的内容是JSON,而不是JSONP。对于JSONP,它应该看起来像这样:'methodName([{“title”:“My Title”}])'其中'methodName'必须作为参数传递。为此,服务器必须支持此协议。你确定远程服务器支持它吗? – 2011-05-11 14:49:16

+0

你所描述的是我遇到的问题。我正在使用http://wordpress.org/extend/plugins/feed-json/并且没有添加?callback = methodName。现在,我应该怎么做,并且使用上面each()中的数据做些什么? – Zoolander 2011-05-11 15:01:03

回答

1

您确定“othersite.com”实际上支持JSONP吗?客户端无法将JSON转换为JSONP。服务器需要支持它使用回调函数来封装内容。

+0

是的,我正在使用WordPress插件Feed JSON:http://wordpress.org/extend/plugins/feed-json/ – Zoolander 2011-05-11 14:50:06

+2

请确保您的网址是http://othersite.com/feed.json?callback= ? – 2011-05-11 14:51:11

+0

我认为这是问题(不使用回调=)。现在我怎么检索item.title,因为数据被封装在callback()中? – Zoolander 2011-05-11 14:52:44

相关问题