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

JSONP solves ajax cross-domain problem (with code)

Apr 26, 2018 pm 02:49 PM
ajax javascript jsonp

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>
Copy after login

test.js code:

alert("success");
Copy after login

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>
Copy after login

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> <div class="code" style="position:relative; padding:0px; margin:0px;"><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>

Copy after login

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"});
Copy after login

  这其实就是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>
Copy after login

  程序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>
Copy after login

像这样的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; 
       } 
     } 
   }
Copy after login

程序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>  
Copy after login

  这就完成了一个最基本的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>
Copy after login

  结果是一样的,要注意的是在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>
Copy after login

  没错,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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

See all articles