将jquery代码转换为跨浏览器Ajax请求的原型以获取最新推文

pra*_*vin 5 javascript twitter ajax jquery prototypejs

将jquery代码转换为跨浏览器Ajax请求的原型

我的第一篇文章!

我必须获取最新的推文,因此不得不执行跨浏览器请求.当前的应用程序使用原型,但我对jquery有点熟悉.

所以,我开始在jquery中:

$.ajax('http://twitter.com/status/user_timeline/apocalyptic_AB.json?count=1&callback=?', {
  dataType: "jsonp",
  success:function(data,text,xhqr){
    $.each(data, function(i, item) {
      console.log(item.text);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

我得到一个警告:

'Resource interpreted as Script but transferred with MIME type application/json.'
Run Code Online (Sandbox Code Playgroud)

但是,我确实看到了我的最后一条推文.精细.

因此,我决定在原型中做同样的事情,然后尝试消除警告,如果有的话.但是,即使在尝试了几个小时后,我也无处可去.

这是我最初在原型中提出的.我接下来发生了很多变化/改动,但都没有.

new Ajax.Request('http://twitter.com/status/user_timeline/apocalyptic_AB.json?count=1&callback=?', {
  contentType: "jsonp",
  onSuccess:function(transport){
    console.log(transport) ;
  }
});
Run Code Online (Sandbox Code Playgroud)

请求成功但响应文本为nil /"".我在Firefox中没有错误,但在Chrome中错误是:

XMLHttpRequest cannot load http://twitter.com/status/user_timeline/apocalyptic_AB.json?count=1&callback=?. Origin http://localhost:4000 is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.谢谢.

pra*_*vin 2

感谢 Darin 让我重新使用 Dandean 的 JSONP 原型 js。

\n\n

虽然我一开始没有提到(问题有点长),但我尝试使用 Dandean 的 Ajax.JSONRequest (您所指的链接)。请求不断失败,我没有进一步使用它,因为我假设在原型中完成它也会非常简单,就像 jquery 一样。由于我没有得到更多答案,所以我决定使用 Ajax.JSONRequest。请求失败并非由于网关超时。这是因为请求 url 中重复了 params 回调。

\n\n

所以,请求的url变成了

\n\n
GET (twitter.com/status/user_timeline/apocalyptic_AB.json?count=1&&callback=?&callba\xe2\x80\x8cck=_prototypeJSONPCallback_0) \n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,我定义了没有回调的 url,并且它按预期执行。\n但是,我仍然收到警告:

\n\n
Resource interpreted as Script but transferred with MIME type application/json\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是等效的原型:

\n\n
new Ajax.JSONRequest('http://twitter.com/status/user_timeline/apocalyptic_AB.json?count=1', {\n    onSuccess:function(response){\n    response.responseJSON.each(function(item){\n        console.log(item.text);\n    });\n
Run Code Online (Sandbox Code Playgroud)\n