Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

json - jQuery getJSON works locally, but not cross domain

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!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...