jQuery getJSON在本地工作,但不是跨域 [英] jQuery getJSON works locally, but not cross domain

查看:228
本文介绍了jQuery getJSON在本地工作,但不是跨域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过FOREVER,无法找到我的问题的确定答案。所以这里。我有一个JSON文件(我去jsonlint验证,它说它的好),看起来像这样(一些信息修改):

  [{
position:1,
category:A,
title:Title to first story,
description :第一个故事。
},
{
position:2,
category:B,
title:
description:第二个故事
},
{
position:3,
category:B,
title:第三个故事的标题,
description:第三个故事
}
]

我使用jQuery来解析和放在html页面上使用这个函数:

 code> $。getJSON('page.json',function(data){
var items = [];

$ .each(data.reponse,function i){
items.push('< li id ='+ i.position +'>'+ i.title +' - '+ i.description +'< / li>') ;
});

$('< ul />',{
'class':'my-new-list',
html: items.join('')
})appendTo('body');
});

它完美的工作!现在来我的问题,JSON文件将不会托管本地,并将实际上托管在一个单独的域。所以我修改我的代码如下(一些阅读后)希望得到它的工作:

  $。getJSON('http: /www.otherdomain.com/page.json?format=json&callback=?',function(data){
var items = [];

$ .each(data.reponse ,function(item,i){
items.push('< li id ='+ i.position +'>'+ i.title +' - '+ i.description +'& / li>');
});

$('< ul />',{
'class':'my-new-list',
html:items.join('')
})appendTo('body');
});

通过添加'回调'行,我停止获取加载资源失败错误。但是,没有发生。它就像我添加的功能是不是没有。我试图把它的所有,并添加一个简单的警报(数据),但是,甚至没有火。我做错了什么?一个大问题是,我100%只限于HTML和JavaScript工作(不是我的选择)。感谢任何帮助!



EDIT
好​​,我没有能力让其他服务器动态添加任何东西到json文件。所以我通过对json(更小的样本)进行硬编码来修改:

  storyData(
[{
position:1,
category:A,
title:第一个故事的标题,
description:第一个故事。
}
])

感谢您的帮助!

解决方案

您需要查看 JSONP



实质上,当您尝试从其他域加载JSON时,它会失败,因为有一个域边界不交叉。要避免这种情况,您必须 PAD (JSONP中的P)。填充它本质上是将它包装在一个函数调用(其中函数名称驻留在您的客户端上)。 正常JSON响应(例如,getjson.php):

  {foo:'bar'} 

JSON回调 parseJSON 例如,getjson.php?callback = parseJSON):

  parseJSON({foo:'bar'})

请注意回调中提供的值如何成为函数的名称你的JSON响应现在被包裹。



然后你的客户端将它传递给 parseJSON ,一个存在于您的客户端(您已定义)的函数。 jQuery(和其他库)尝试通过生成一些随机函数,然后通过您的原始回调发送响应(所有这一切都是在底层完成)为您照顾这一点。



如果您可以控制生成JSON的服务器页面,请实现一个回调方法,以便您可以提供如何包装JSON,以便您可以在最后使用它。 (只有在处理来自客户端当前所在网页之外的域的数据时,才需要这样做)。






< h2> UPDATE

为了基本解决你遇到的问题,你需要找到一种方法来将你的JSON信息传入JSONP调用。不知道你的page.json是什么语言,这里是它应该包含的伪代码逻辑:

 如果GET_VARIABLE (callback)

打印GET_VARIABLE(callback)和一个打开的括号
打印正常的JSON数据
打印关闭括号

else

打印正常的JSON数据

结束if

如果你决定硬编码函数名,而不是允许它作为回调在url中提供,那么你需要记住它。对于下一个示例,让我们假设我们将其命名为 MyJSONPCallback



现在,在客户端代码中,您可以继续使用:

  $。ajax({
url:'http://anotherdomain.com/page.json?format=json',
dataType:'json',
jsonpCallback:'MyJSONPCallback',//指定回调名称如果你是硬编码的
success:function(data){
/ /我们使一个成功的JSONP调用!
}
});


I've searched FOREVER and can't come up with a definitive answer to my problem. So here it is. I have a JSON file (I went to jsonlint to validate and it says its good) that looks like this (some information modified):

[{
        "position":"1",
        "category":"A",
        "title":"Title to first story",
        "description":"The first story."
    },
    {
        "position":"2",
        "category":"B",
        "title":"Title to second story",
        "description":"The second story"
    },
    {
        "position":"3",
        "category":"B",
        "title":"Title to third story",
        "description":"The third story"
    }
]

I used jQuery to parse through and put on an html page using this function:

$.getJSON('page.json', function(data) {
  var items = [];

  $.each(data.reponse, function(item, i) {
    items.push('<li id="' + i.position + '">' + i.title + ' - ' + i.description + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

It works perfectly! Now comes my issue, the JSON file will not be hosted locally, and will in fact be hosted on a separate domain. So I modified my code as follows (after some reading) hoping to get it working:

$.getJSON('http://www.otherdomain.com/page.json?format=json&callback=?', function(data) {
  var items = [];

  $.each(data.reponse, function(item, i) {
    items.push('<li id="' + i.position + '">' + i.title + ' - ' + i.description + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

By adding the 'callback' line I stopped getting a "Failed to load resource" error. However, nothing is happening. It is like the function I added isn't even there. I tried to take all of it out and add a simple 'alert(data)', but that didn't even fire. What am I doing wrong? A big problem is that I am 100% limited to just HTML and JavaScript to work (not my choice). Thanks for any help!

EDIT Ok, I don't have ability for the other server to dynamically add anything to the json file. So I modified by hardcoding a function around the json (smaller sample):

storyData(
[{
        "position":"1",
        "category":"A",
        "title":"Title to first story",
        "description":"The first story."
    }
])

Everything now works! Thanks for all the help!

解决方案

You need to look in to JSONP.

Essentially, when you try to load JSON from another domain, it fails because there is a domain boundary you can not cross. To avoid this, you have to PAD it (P in JSONP). Padding it is essentially wrapping it in a function call (where the function name resides on your client.) e.g. a "normal" JSON response (say, for example, getjson.php):

{foo:'bar'}

JSON with a callback of parseJSON becomes (Say, for example, getjson.php?callback=parseJSON):

parseJSON({foo:'bar'})

Notice how the value that was supplied in callback becomes the name of the function your JSON response is now wrapped in.

Then your client will want to pass it to parseJSON, a function that exists on your client (that you've defined). jQuery (and other libraries) try to take care of this for you by generating some "random" function and then sending the response back through your original callback (all this is done under the hood).

If you have control over the server page generating the JSON, implement a callback method so you can supply how the JSON should be wrapped so you can then work with it on your end. (This is only necessary when you're dealing with data from a domain other than the page the client is currently on).


UPDATE

To basically solve the problem you're having, you need to find a way to get your JSON information in to a JSONP call. Without knowing what language your "page.json" is in, here's the pseudo-code logic that it should contain:

if GET_VARIABLE("callback") is supplied

  print GET_VARIABLE("callback") and an open parenthesis
  print normal JSON data
  print closing parenthesis

else

  print normal JSON data

end if

If you decide to hard-code the function name instead of allow it to be supplied in the url as "callback", then you need to remember it. For the next example, let's imagine we named it MyJSONPCallback

Now, in your client code, you can go ahead of use:

$.ajax({
  url: 'http://anotherdomain.com/page.json?format=json',
  dataType: 'json',
  jsonpCallback: 'MyJSONPCallback', // specify the callback name if you're hard-coding it
  success: function(data){
    // we make a successful JSONP call!
  }
});

这篇关于jQuery getJSON在本地工作,但不是跨域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆