开发者

JSONP and XMLHttpRequest question

开发者 https://www.devze.com 2023-03-23 02:21 出处:网络
Am trying to understand the same origin policy in browsers (and also Javascript newbie) and ran into the JSONP page on wikipedia. The How It Works section says -

Am trying to understand the same origin policy in browsers (and also Javascript newbie) and ran into the JSONP page on wikipedia. The How It Works section says -

Now, consider that it is possible to specify any URL, including a URL that returns JSON, as the src > attribute for a element. This means it is possible to retrieve JSON via a script element in > an HTML page.

However, a JSON document is not a JavaScript program. If it is to be evaluated by the browser 开发者_如何转开发in a element, the return value from the src URL must be executable JavaScript. In the JSONP usage pattern, the URL returns the dynamically-generated JSON, with a function call wrapped around it. This is the "padding" (or sometimes, "prefix") of JSONP.

My questions are -

  • So is XMLHTTPRequest() supposed to return only javascript or html? Can it not return a pure json document?
  • I thought the same origin policy does not apply to XMLHttpRequest() call. Why is there a need to inject a tag into the DOM to make a call to a third party server? Is that how all the advertising add-ons to sites call home to collect data?
  • At the end of it I did not understand JSONP at all. Can some one explain or refer me to a better explanation please?

Thanks,

- P


So is XMLHTTPRequest() supposed to return only javascript or html?

It can return any text you like (and maybe binary data, but I've never see that tried so I won't swear to it)

Can it not return a pure json document?

It can.

I thought the same origin policy does not apply to XMLHttpRequest() call.

The same origin policy most definitely does apply to XHR

Why is there a need to inject a tag into the DOM to make a call to a third party server?

The same origin policy is bypassed by loading a script (with embedded data) from another origin.

This is because you aren't reading a remote resource using JavaScript. You are executing some remote JavaScript which comes with embedded data.

At the end of it I did not understand JSONP at all. Can some one explain or refer me to a better explanation please?

JSON-P is just loading some JavaScript from another origin. That JavaScript consists of a single function call (to a function you define before adding the <script> element) with a single argument (a JS object or array literal).

0

精彩评论

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