Home > Web Front-end > JS Tutorial > How to send JSONP requests using Script elements (graphic tutorial)

How to send JSONP requests using Script elements (graphic tutorial)

亚连
Release: 2018-05-21 10:12:13
Original
1354 people have browsed it

Below I will bring you an article on how to use Script elements to send JSONP requests. Let me share it with you now and give it as a reference for everyone.

How to use Script elements to send JSONP requests

// 根据指定URL发送一个JSONP请求 
//然后把解析得到的相应数据传递给回调函数 
//在URL中添加一个名为jsonp的查询参数,用于指定该请求的回调函数的名称 
function getJSONP(url, callback){ 
 //为本次请求创建一个唯一的回调函数名称 
 var cbnum = "cb"+getJSONP.counter++; 
 var cbname = "getJSONP."+cbnum;   
 
 if(url.indexof("?") === -1){ 
  url += "?jsonp="+cbname; 
 }else { 
  url += "&jsonp="+cbname; 
 } 
 
 var script = document.createElement("script"); 
 
 getJSONP[cbnum] = function(response){ 
  try{ 
   callback(response); 
  }finally{ 
   delete getJSONP[cbnum]; 
   script.prentNode.removeChild(script); 
   }  
  }; 
 
  script.src = url; 
  document.body.appendChild(script); 
 
} 
 
getJSONP.counter = 0;
Copy after login

The above is what I compiled Everyone, I hope it will be helpful to everyone in the future.

Related articles:

JavaScript dynamically changes HTML page elements such as adding or deleting

Use p5.js to create fireworks effects Sample code_javascript skills

Detailed explanation of the combination of JavaScript and HTML

The above is the detailed content of How to send JSONP requests using Script elements (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template