JavaScript implements JSONP code manually

Source: Internet
Author: User

The browser's same-origin policy does not allow us to directly through the AJAX call the URL on the domain name, but the script,img tag but the meter has this limitation, JSONP is to take advantage of this, by generating a page src for the URL we want to invoke the script tag, Can get the result of the server return, of course, this only supports GET request, also, the server side should be able to accept the parameters we passed.

Here is an example:

<script>functionRemovescript (scriptid) {Const script=document.getElementById (Scriptid); document.getElementsByTagName (' head ') [0].removechild (script);}functionclearfunction (functionname) {Try {    DeleteWindow[functionname];//IE8 Direct deletion will error}Catch(e) {Window[functionname]=undefined; }}functionCall (URL) {varCallbackfunction = Math.ceil (Math.random () * 100000 ); URL+ = (url.indexof ('? ') = = =-1)? '? ': ' & '; varJsonpscript = document.createelement (' script '); Jsonpscript.setattribute (' src ', ' ${url}callabck=${callbackfunction} '); Jsonpscript.id=Scriptid; document.getElementsByTagName (' head ') [0].appendchild (Jsonpscript); Window[callbackfunction]=function(data) {//process the data here, and then finally remember to delete the script and remove the function from the Window object.          //Handling Data ...Removescript (Scriptid);    Clearfunction (callbackfunction); }}</script>

JavaScript implements JSONP code manually

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.