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