Search code examples
jqueryajaxjsonsame-origin-policy

What has to be changed client-side or server-side to make getJSON() work?


I'm working with some web services that have already been created and I need to call them using ajax. The site I'm working on is hosted in a different domain than that of the web services. I'm now aware of the problems this causes with the same-origin policy.

I'm trying to get round it using JSON, based on articles:

JQuery API

IBM on cross-domain comms

and tonnes of other questions on here.

I have tried the following code (replaced actual domain with "webservice"):

    <script type="text/javascript">
          $(document).ready(function(){
        $.getJSON("http://webservice/restserver.aspx?",
        {
            method: "userInfo",
            userID: "039304303930302",
            sessionID: "STRING",
                format: "json"

        },
         function(data) {
                alert("GET Returned");
        });

});
</script>

1) Is there anything terribly wrong with this as I'm new to JSON and AJAX

2) Does the web service need to have a callback e.g.- "&callback=?" added to it

3) Is there any other way to get around cross-domain calls

Any suggestions or help will be most welcome as I have working on this for ages.

Thanks!


Solution

  • You need JSONP which is different than JSON. You need to modify the web service method so that it can take an additional argument (for example callback=foo) and would wrap the JSON response in this function:

    foo({ first_name: 'john', last_name: 'smith' })
    

    Also to implement cross domain AJAX calls jQuery uses a hidden <script> tag so the web service must be configured to accept GET requests.

    The $.getJSON() method documentation contains an example using Flickr which you could try running and looking at the exact request/response with FireBug. You may see it in action here.