跨域 jquery ajax 未获取 json

发布于 2024-12-15 10:42:15 字数 1611 浏览 2 评论 0原文

我只是创建了一个 Rails 3.0 脚手架并使用 json 公开它,并保持它运行。

因此,如果我点击 http://localhost:3001/objects.json

我会在浏览器中看到 json 数据

接下来我有一个纯 html,其中包括 code.jquery.com/jquery-1.7.min.js。我在 firefox(ubuntu) 中打开此页面,然后打开 firebug 控制台并尝试按照

var myurl = 'http://localhost:3001/objects.json';

$.ajax({
url: myurl,
dataType: 'jsonp',
error: function(data){ console.log("error:"+data); console.log("error:"+data.readyState); },
success: function(data){ console.log("success:"+data); }
});

我想在成功处理程序中获取相同的 json ,到目前为止我观察到的是,

如果指定 dataType: 'jsonp'

  1. 我确实得到 json 响应(已检查与 firebug:Net) 一样,就像我在浏览器中看到的那样,
  2. 我没有得到成功调用
  3. ,我确实得到了错误调用,状态代码= 4,状态=“成功”,

否则我得到的

响应为空白

,还有一件事,每次我得到200回来。

有任何提示...这里发生了什么事吗?

添加我的服务器端代码和日志

代码=>

# GET /objects
# GET /objects.json
def index
  @objects = Object.all

  respond_to do |format|
    format.html # index.html.erb
    format.json  {
      render :json => @objects.to_json, :layout => nil
      }
  end
end

日志样本=>

Started GET "/objects.json?callback=jQuery17024293556233345082_1321347517236&_=1321347853199" for 127.0.0.1 at 2011-11-15 14:34:13 +0530
  Processing by objectsController#index as JSON
  Parameters: {"callback"=>"jQuery17024293556233345082_1321347517236",     "_"=>"1321347853199"}
  [1m[35mobject Load (0.1ms)[0m  SELECT `objects`.* FROM `objects`
Completed 200 OK in 11ms (Views: 5.4ms | ActiveRecord: 0.1ms)

I simply created a rails 3.0 scaffold and exposed it using json, and kept it running.

So if I hit http://localhost:3001/objects.json

I see json data in browser

Next I have one plain html which includes code.jquery.com/jquery-1.7.min.js. I opened this page in firefox(ubuntu), then opened the firebug console and tried following

var myurl = 'http://localhost:3001/objects.json';

$.ajax({
url: myurl,
dataType: 'jsonp',
error: function(data){ console.log("error:"+data); console.log("error:"+data.readyState); },
success: function(data){ console.log("success:"+data); }
});

I wanted to fetch same json here in success handler, what I have observed so far is

if specified dataType: 'jsonp'

  1. I do get json response(checked with firebug:Net), same as I see in browser
  2. I do not get success called
  3. I do get error called, with status code = 4, and status = "success"

else I get

response blank

And one more thing, every time I get 200 back.

Any hints ...whats going on here?

Adding my server side code and log

code =>

# GET /objects
# GET /objects.json
def index
  @objects = Object.all

  respond_to do |format|
    format.html # index.html.erb
    format.json  {
      render :json => @objects.to_json, :layout => nil
      }
  end
end

log sample =>

Started GET "/objects.json?callback=jQuery17024293556233345082_1321347517236&_=1321347853199" for 127.0.0.1 at 2011-11-15 14:34:13 +0530
  Processing by objectsController#index as JSON
  Parameters: {"callback"=>"jQuery17024293556233345082_1321347517236",     "_"=>"1321347853199"}
  [1m[35mobject Load (0.1ms)[0m  SELECT `objects`.* FROM `objects`
Completed 200 OK in 11ms (Views: 5.4ms | ActiveRecord: 0.1ms)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

养猫人 2024-12-22 10:42:15

我认为你使用 $.getJSON 可能会更好

I think you using $.getJSON may be better

那一片橙海, 2024-12-22 10:42:15

也许您返回的结果是错误的 Content-type (不是 jsonp)。如果您希望 jQuery 触发“成功”事件而不管 Content-type,请从 ajax 选项中删除 dataType 参数

Maybe you returning result in the wrong Content-type (not jsonp). If you want jQuery to fire 'success' event regardless the Content-type, remove dataType parameter from ajax options

别低头,皇冠会掉 2024-12-22 10:42:15

首先,我猜测它应该是 Object.all

我假设您发出请求的服务器与为您提供 JSON 数据的服务器不同。即在这种情况下有不同的端口,或者我认为不需要使用 JSONP。

JSONP 不是 ajax,但在脚本标签中使用 src 属性。如果您尝试从同一服务器访问信息,则应该采用 dataType: json 方法。

如果您从不同的服务器获取信息,我建议您在 url 流的末尾添加 ?callback=?

对于 Jquery $.getJSON 应该是可行的方法。例如

<代码>
$.getJSON(url, 数据, 函数(响应){
// 做一些有响应的事情;
});

参考http://api.jquery.com/jQuery.getJSON/

中引用您最后的评论使用此格式。



$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){});

  });


更新
只记得这一点,如果您可以控制两台服务器,您是否会发送 JSONP 响应?如果这是您的 JSON 数据,


response = { status:'success', message:'Successfully created object'}

要将其作为 JSONP 发送,您必须将其包装在 function() 中。就像


jsoncallback + "(" + JSON.stringify(response)  + ");";

它的作用是执行 Jquery 生成的函数(这是在指定回调=?时在内部完成的。您可以通过检查 localhost:3001 日志获取该值)并将 JSON 数据作为参数传递给该函数。

因此,如果在服务器端您没有生成 JSON-P 响应,它将无法工作。

First, I am guessing it should be Object.all

I am assuming that the server your requesting from is different from the server that provides you with JSON data. i.e. different ports in this case or I see no need to use JSONP.

JSONP is not ajax but uses the src attributes in the script tags. If your trying to access information from the same server it dataType: json should be the approach.

If you are fetching information from a different server i suggest you add to the end of your url stream a ?callback=?.

With Jquery $.getJSON should be the way to go. For example


$.getJSON(url, data, function(response){
// Do something with response;
});

Reference http://api.jquery.com/jQuery.getJSON/

In reference to your last comment use this format.



$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){});

  });


Update
Just remembered this bit, If you have control over both servers are you sending JSONP responses? If this is your JSON data


response = { status:'success', message:'Successfully created object'}

To send it as JSONP you must wrap it up in a function(). Like


jsoncallback + "(" + JSON.stringify(response)  + ");";

What this does is it executes the function generated by Jquery (this is done internally when specifiy callback=?. You can get the value by checking localhost:3001 logs) and passes your JSON data as parameters to that.

So if on the server side you are not generating JSON-P response it wont work.

ぃ双果 2024-12-22 10:42:15

很久以前我们就遇到过类似的问题,尽管是使用 json,而不是 jsonp。而且这不是跨域问题。根据我的记忆,我相信我们必须从控制器中删除 respond_to 并提供 :status => 200 渲染方法使其正常工作。我不太确定,但你可以尝试一下。

We ran into a similar issue once long back, although with json, not jsonp. And it wasn't a cross-domain problem. Counting on my memory, I believe we had to remove respond_to from the controller and provide :status => 200 to render method to get it working. I'm not very sure, but you could give it a shot.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文