开发者

What must I do to circumvent the JavaScript same-origin policy for JSON... And can that work for XML data as well?

开发者 https://www.devze.com 2023-02-01 05:00 出处:网络
I have question about the same origin policy... I have JavaScript code using JSON and XML data. I know I need to change JSON to JSONP, since my server is on a different domain, but do I only do that

I have question about the same origin policy...

I have JavaScript code using JSON and XML data. I know I need to change JSON to JSONP, since my server is on a different domain, but do I only do that in the client side? And what about the XML data? Can that also be loaded cross-domain somehow?

Finally, are there any good websites explaining this 开发者_运维百科in-depth, with examples?


Encode your XML inside your jsonp response, and then make your client extract it and interpret it as XML.


You do have to modify the server. You can use JSONP's principle for XML. You just have to pass a string:

E.g. assume your server-side program is at /xmlp . You pass a callback parameter, then the script wraps the XML output in this.

E.g.

/xmlp?callback=mycall

outputs:

mycall('<root><el attr="value"/ ></root>');

You then parse the XML (passed into a JavaScript mycall function) on the client side.


As soon as you datasource is in different domain, you have to use JSONP to get data. This is both for JSON and XML data. JSONP is just a notatation, that makes you available to supply a callback function and it would be called as soon as remote call finished. Data is provided as callback parameter.

Of cause, you API must support JSONP, as soon as request to API contains "?callback=f", it must return something like

{ f(data); }

and f - is function defined somewhere on your page.

So, basically as API call finished, you call back function is called.

You have several options to use API from different origin

  1. With YQL - http://developer.yahoo.com/yql/
  2. Manually, pure JS or with jQuery - http://www.beletsky.net/2010/07/json-jsonp-and-same-origin-policy-issue.html
0

精彩评论

暂无评论...
验证码 换一张
取 消