The policy disallows reading any responses sent by websites whose origins are different from the one currently used. Incidentally, the policy allows sending a request, but not reading one. If you wish to learn more about this policy, look no further. But due to the aforementioned policy, the request would be blocked because the origins of the website and the server differ. In this case, the returned code would be the JSON snippet shown above. In the returned code, a function is wrapped around the JSON object.
The function name has to be passed by the client since the code is going to be executed in the browser. The function name is provided in the query parameter called callback. Then we increment the jsonpID to make sure the function name is unique. Inside the query, we set the callback parameter to equal callbackName.
We also set the async attribute to true in order for the script to be non-blocking. Executing a function called callback in the global scope is equivalent to calling window. This popular article was updated on 23rd June, to address quality issues. Comments pertaining to the old article were removed. This is an important concept in the browser security model and dictates that a web browser may only allow scripts on page A to access data on page B if these two pages have the same origin.
The origin of a page is defined by its protocol , host and port number. The same-origin policy is a saftey mechanism. It prevents scripts from reading data from your domain and sending it to their servers. Unfortunately, it also causes the error we see above and often poses a headache for developers trying to accomplish a legitimate task. Next, add a script tag to your page which calls the API and passes it an additional parameter. Notice the additional parameter?
This is crucial! So for us, the API would return:. So myCallbackFunction gets called. You can get jQuery to do that for you : To make the same call as we did previously you can just use:. Safety First! The handy reason is that if you owned the API you almost certainly would not want randoms from the internet updating your data.
0コメント