Home >Web Front-end >JS Tutorial >JSONP solves ajax cross-domain problem (with code)

JSONP solves ajax cross-domain problem (with code)

php中世界最好的语言
php中世界最好的语言Original
2018-04-26 14:49:111747browse

This time I will bring you JSONP to solve ajax cross-domain problems (with code). What are the precautions for JSONP to solve ajax cross-domain problems. The following is a practical case, let's take a look.

JSON and JSONP

JSONP and JSON look alike. Is there any connection between them?

JSON (JavaScript Object Notation) is a lightweight data exchange format. Everyone should be familiar with JSON. Friends who are not very familiar with it can go to json.org to learn about it. It is simple and easy to understand.

JSONP is the abbreviation of JSON with Padding. It is an unofficial protocol that allows integrating Script tags on the server side and returning them to the client, enabling cross-domain access in the form of javascript callbacks (this is just a simple implementation of JSONP).

JSONP is just like JSON Padding (Padding here we understand as filling), let’s look at the following small example first and then introduce it in detail.

Same Origin Policy

Why does such an error occur? This is because all browsers that support Javascript use the same-origin policy. Take a look at Baidu’s explanation:

Same-origin policy is a well-known security policy proposed by Netscape. All browsers that support JavaScript now use this strategy. The so-called same origin means that the domain name, protocol and port are the same. When Baidu and Google pages are opened in two tab pages of a browser, when a Baidu browser executes a script, it will check which page the script belongs to, that is, check whether it has the same origin. Only the same origin as Baidu The script will be executed.

This is the reason why the data cannot be obtained. So how can we solve the cross-domain problem? That's right, we can now get to the point and understand what JSONP is.

The simple principle of cross-domain

It’s not very clear just by looking at the definition, so first let’s do a simple and easy-to-understand test manually. Create a new web program of asp.net, add the sample.html web page and a test.js file, the code is as follows:

sample.html code:

 <!DOCTYPE html PUBLIC "-//WC//DTD XHTML . Transitional//EN" "http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd">
 <html xmlns="http://www.w.org//xhtml" >
 <head>
   <title>test</title>
   <script type="text/javascript" src="test.js"></script>
 </head>
 <body>
 </body>
 </html>

test.js code:

alert("success");

After opening sample.html, a message box like "success" will pop up. This does not seem to mean anything. Cross-domain How to solve the problem? Okay, now we simulate a non-homogeneous environment. Didn’t we just use Visual Studio to create a new Web program (here we call it program A). Now we open a new Visual Studio and create a new Web program (program B). ), remove our previous test.js file from program A and copy it to program B. After both programs are running, Visual Studio will start the built-in server. Assume that program A is localhost:20001 and program B is localhost:20002. This simulates a non-homogeneous environment (although the domain name is the same but the port number is different, So it is non-homogeneous).

OK, we should change the code in sample.html next, because the test.js file is in program B, and the url becomes localhost:20002.

sample.html part of the code:

<script type="text/javascript" src="http://localhost:20002/test.js"></script>

Please keep the two web programs AB running. When you refresh localhost:20001/sample.html again, The "success" dialog box pops up just like before. Yes, the so-called remote service of localhost:20002/test.js, which is not from the same origin, was successfully accessed. At this point, I believe everyone should have a rough understanding of the principles of cross-domain access.

 The src attribute of the <script> tag is not restricted by the same-origin policy, so you can obtain and execute any script on the server. </p> <p style="text-align: left;"><span style="background-color: #808080">JSONP implementation mode--CallBack</span></p> <p style="text-align: left;"> The small example just explained the principle of cross-domain. Let’s go back and look at the definition of JSONP and talk about javascript. callback form. Then let's modify the code and how to implement the javascript callback form of JSONP. </p> <p style="text-align: left;">Part of the sample code in program A: </p> <pre class="brush:php;toolbar:false"> <script type="text/javascript">  //回调函数  function callback(data) {     alert(data.message);   }   </script>   <script type="text/javascript" src="http://localhost:20002/test.js"></script>

The code of test.js in program B:

//Call the callback function and pass it as an explanation in the form of json data ,Complete callback

callback({message:"success"});

  这其实就是JSONP的简单实现模式,或者说是JSONP的原型:创建一个回调函数,然后在远程服务上调用这个函数并且将JSON 数据形式作为参数传递,完成回调。

  将JSON数据填充进回调函数,这就是JSONP的JSON+Padding的含义吧。

  一般情况下,我们希望这个script标签能够动态的调用,而不是像上面因为固定在html里面所以没等页面显示就执行了,很不灵活。我们可以通过javascript动态的创建script标签,这样我们就可以灵活调用远程服务了。

程序A中sample的部分代码:

 <script type="text/javascript"> 
   function callback(data) { 
     alert(data.message); 
   } 
   //添加<script>标签的方法 
   function addScriptTag(src){ 
   var script = document.createElement('script'); 
     script.setAttribute("type","text/javascript"); 
     script.src = src; 
     document.body.appendChild(script);
   } 
 
   window.onload = function(){ 
     addScriptTag("http://localhost:/test.js"); 
   } 
 </script>

  程序B的test.js代码不变,我们再执行下程序,是不是和原来的一样呢。如果我们再想调用一个远程服务的话,只要添加addScriptTag方法,传入远程服务的src值就可以了。这里说明下为什么要将addScriptTag方法放入到window.onload的方法里,原因是addScriptTag方法中有句document.body.appendChild(script);,这个script标签是被添加到body里的,由于我们写的javascript代码是在head标签中,document.body还没有初始化完毕呢,所以我们要通过window.onload方法先初始化页面,这样才不会出错。

  上面的例子是最简单的JSONP的实现模型,不过它还算不上一个真正的JSONP服务。我们来看一下真正的JSONP服务是怎么样的,比如Google的ajax搜索接口:http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?&callback=?

  q=?这个问号是表示你要搜索的内容,最重要的是第二个callback=?这个是正如其名表示回调函数的名称,也就是将你自己在客户端定义的回调函数的函数名传送给服务端,服务端则会返回以你定义的回调函数名的方法,将获取的json数据传入这个方法完成回调。有点罗嗦了,还是看看实现代码吧:

 <script type="text/javascript"> 
   //添加<script>标签的方法 
   function addScriptTag(src){
     var script = document.createElement('script');
     script.setAttribute("type","text/javascript");
     script.src = src;
     document.body.appendChild(script);
   }
   window.onload = function(){
     //搜索apple,将自定义的回调函数名result传入callback参数中
     addScriptTag("http://ajax.googleapis.com/ajax/services/search/web?v=.&q=apple&callback=result");
   }
   //自定义的回调函数result
   function result(data) {
     //我们就简单的获取apple搜索结果的第一条记录中url数据
     alert(data.responseData.results[].unescapedUrl);
   }
 </script>

像这样的JSONP服务还有很多(以下信息来自使用 JSONP 实现跨域通信,第 1 部分: 结合 JSONP 和 jQuery 快速构建强大的 mashup):

接下来我们自己来创建一个简单的远程服务,实现和上面一样的JSONP服务。还是利用Web程序A和程序B来做演示,这次我们在程序B上创建一个MyService.ashx文件。

程序B的MyService.ashx代码:

 public class MyService : IHttpHandler 
   { 
     public void ProcessRequest(HttpContext context) 
     { 
       //获取回调函数名 
       string callback = context.Request.QueryString["callback"]; 
       //json数据 
       string json = "{\"name\":\"chopper\",\"sex\":\"man\"}"; 
 
       context.Response.ContentType = "application/json"; 
       //输出:回调函数名(json数据)
       context.Response.Write(callback + "(" + json + ")");
     } 
 
     public bool IsReusable 
     { 
       get 
       { 
         return false; 
       } 
     } 
   }

程序A的sample代码中的调用:

 <script type="text/javascript">   function addScriptTag(src){
     var script = document.createElement('script');
     script.setAttribute("type","text/javascript");
     script.src = src;
     document.body.appendChild(script);
   }
    window.onload = function(){
     //调用远程服务     addScriptTag("http://localhost:/MyService.ashx?callback=person");
   }
   //回调函数person   function person(data) {
     alert(data.name + " is a " + data.sex);
   }
 </script>  

  这就完成了一个最基本的JSONP服务调用了,是不是很简单,下面我们来了解下JQuery是如何调用JSONP的。

jQuery对JSONP的实现

  jQuery框架也当然支持JSONP,可以使用$.getJSON(url,[data],[callback])方法(详细可以参考http://api.jquery.com/jQuery.getJSON/)。那我们就来修改下程序A的代码,改用jQuery的getJSON方法来实现(下面的例子没用用到向服务传参,所以只写了getJSON(url,[callback])):

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript">  
 $.getJSON("http://localhost:20002/MyService.ashx?callback=?",
function(data){     alert(data.name + " is a a" + data.sex);   }); 
</script>

  结果是一样的,要注意的是在url的后面必须添加一个callback参数,这样getJSON方法才会知道是用JSONP方式去访问服务,callback后面的那个问号是内部自动生成的一个回调函数名。这个函数名大家可以debug一下看看,比如jQuery17207481773362960666_1332575486681。

  当然,加入说我们想指定自己的回调函数名,或者说服务上规定了固定回调函数名该怎么办呢?我们可以使用$.ajax方法来实现(参数较多,详细可以参考http://api.jquery.com/jQuery.ajax)。先来看看如何实现吧:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript">  
 $.ajax({     url:"http://localhost:20002/MyService.ashx?callback=?",      
dataType:"jsonp",     jsonpCallback:"person",     
success:function(data){       
alert(data.name + " is a a" + data.sex);     }  }); 
</script>

  没错,jsonpCallback就是可以指定我们自己的回调方法名person,远程服务接受callback参数的值就不再是自动生成的回调名,而是person。dataType是指定按照JSOPN方式访问远程服务。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

AJAX二级联动有哪些实现方法

php+jquery传递json数据实现方法

The above is the detailed content of JSONP solves ajax cross-domain problem (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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