简体   繁体   中英

Is it possible to use javascript to download JSON object from another domain/server?

那段代码会是什么样的?

That other domain/server needs to support JSONP, which basically wraps the JSON in a callback.

In jQuery, the call would look like this:

$.getJSON(
     'http://otherdomain.com/api/whatever?callback=?', 
     { key: 'value', otherkey: true },
     function(data){
        //handle response
     }
);

The actual response from the other server (if you looked at what was actually being sent) would look like this:

// With this url:
http://domain.com/api/method?callback=the_callback_function_name

// The response would look like this:
the_callback_function_name({ "json": "data here"});

The jQuery getJSON method automatically handles JSONP when you supply the extra callback=? . Just keep in mind some sites using different names like json_callback=? . The important part is that you include it as part of the URL and don't try to add callback: '?' to the data part of the getJSON function.

Only via JSONP. Whether you use jQuery or some other framework, it boils down to a script block like this:

<script type="text/javascript" src="http://path.to/your/javascript"></script>

The <script> block is immune from cross-domain restrictions. The caveat is that the service should support JSONP as well. If the script returns a JSON object like this:

{a: 0, b: 1}

The object will be evaluated but nothing happens. But JSONP services accept a callback function name something like this

<script type="text/javascript" src="http://path.to/your/javascript?callback=yourCallbackFunction"></script>

and wrap the data as a parameter to your callback like this:

yourCallbackFunction({a: 0, b: 1});

So that the function is called when the script is evaluated.

You can use JSONP. in jQuery, try getJSON: http://api.jquery.com/jQuery.getJSON/

Instead you should use a local proxy. Set up a asp.net/php page that will load the remote page on the back end and then use ajax to load the proxy page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM