search
HomeWeb Front-endJS TutorialAJAX cross-domain request JSONP to obtain JSON data

AJAX cross-domain request JSONP to obtain JSON data

May 24, 2018 pm 05:25 PM
javascriptjsonjsonp

JSONP (JSON with Padding) 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 callback (this is just a simple implementation of JSONP).

Asynchronous JavaScript and XML (Ajax) is a key technology driving a new generation of Web sites (popularly known as Web 2.0 sites). Ajax allows data retrieval in the background without interfering with the display and behavior of the Web application. Get data using the XMLHttpRequest function, an API that allows client-side JavaScript to connect to a remote server over HTTP. Ajax is also the driving force behind many mashups, which integrate content from multiple places into a single Web application.

However, due to browser restrictions, this method does not allow cross-domain communication. If you try to request data from a different domain, a security error will occur. These security errors can be avoided if you can control the remote server where the data resides and if every request goes to the same domain. But what good is a web application if it just stays on its own server? What if you need to collect data from multiple third-party servers?

Understanding Same Origin Policy Restrictions

The Same Origin Policy prevents scripts loaded on one domain from obtaining or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is old and has existed since Netscape Navigator version 2.0.

A relatively simple way to overcome this limitation is to have the web page request data from the web server it originated from, and have the web server act like a proxy and forward the request to the actual third-party server. Although this technology has gained widespread use, it is not scalable. Another way is to use frame elements to create a new area within the current web page and use GET requests to obtain any third-party resources. However, after obtaining the resources, the content in the frame will be restricted by the same-origin policy.

A more ideal way to overcome this limitation is to insert a dynamic script element into a Web page whose source points to a service URL in another domain and fetches the data in its own script. It starts executing when the script loads. This approach works because the Same Origin Policy does not prevent dynamic script insertion and the script is treated as if it were loaded from the domain that serves the Web page. But if the script tries to load the document from another domain, it won't succeed. Fortunately, this technique can be improved upon by adding JavaScript Object Notation (JSON).

1. What is JSONP?

To understand JSONP, we have to mention JSON. So what is JSON?

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

JSONP(JSON with Padding ) 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 callback (this is just a simple implementation of JSONP).

2. What is the use of JSONP?

Due to the restriction of the same-origin policy, XmlHttpRequest only allows requests for resources from the current source (domain name, protocol, port). In order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then in the service The end outputs JSON data and executes the callback function, thus solving cross-domain data requests.

3. How to use JSONP?

The DEMO below is actually a simple representation of JSONP. After the client declares the callback function, the client requests cross-domain data from the server through the script tag, and then the server returns the corresponding data and Dynamically execute callback functions.

HTML code (either):

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<script type="text/javascript"> 
  function jsonpCallback(result) { 
    //alert(result); 
    for(var i in result) { 
      alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
    } 
  } 
  var JSONP=document.createElement("script"); 
  JSONP.type="text/javascript"; 
  JSONP.src="http://crossdomain.com/services.php?callback=jsonpCallback"; 
  document.getElementsByTagName("head")[0].appendChild(JSONP); 
</script>

or

Html code

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<script type="text/javascript"> 
  function jsonpCallback(result) { 
    alert(result.a); 
    alert(result.b); 
    alert(result.c); 
    for(var i in result) { 
      alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
    } 
  } 
</script> 

<script type="text/javascript" src="http://crossdomain.com/services.php?callback=jsonpCallback"></script>

JavaScript The link must be below the function.

Server-side PHP code (services.php):

<?php 
//服务端返回JSON数据 
$arr=array(&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>4,&#39;e&#39;=>5); 
$result=json_encode($arr); 
//echo $_GET[&#39;callback&#39;].&#39;("Hello,World!")&#39;; 
//echo $_GET[&#39;callback&#39;]."($result)"; 
//动态执行回调函数 
$callback=$_GET[&#39;callback&#39;]; 
echo $callback."($result)";

If the above JS client code is implemented using jQuery, it is also very simple.

$.getJSON
$.ajax
$.get

Implementation method of client JS code in jQuery 1:

Js code

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
  $.getJSON("http://crossdomain.com/services.php?callback=?", 
  function(result) { 
    for(var i in result) { 
      alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
    } 
  }); 
</script>

Implementation method 2 of client JS code in jQuery:

Js code

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
  $.ajax({ 
    url:"http://crossdomain.com/services.php", 
    dataType:&#39;jsonp&#39;, 
    data:&#39;&#39;, 
    jsonp:&#39;callback&#39;, 
    success:function(result) { 
      for(var i in result) { 
        alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
      } 
    }, 
    timeout:3000 
  }); 
</script>

Client JS code in jQuery Implementation method 3:

Js code

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
  $.get(&#39;http://crossdomain.com/services.php?callback=?&#39;, {name: encodeURIComponent(&#39;tester&#39;)}, function (json) { for(var i in json) alert(i+":"+json[i]); }, &#39;jsonp&#39;); 
</script>

Among them, jsonCallback is registered by the client and is a callback function after obtaining the json data on the cross-domain server.
http://crossdomain.com/services.php?callback=jsonpCallback
This url is the interface for the cross-domain server to obtain json data. The parameter is the name of the callback function, and the returned format is

Js code

jsonpCallback({msg:&#39;this is json data&#39;})

Jsonp principle:

First register a callback on the client, and then pass the callback name to the server.

At this time, the server first generates json data.

Then use javascript syntax to generate a function. The function name is the passed parameter jsonp.

Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the data is passed as a parameter to the callback function predefined by the client. (Dynamic execution of the callback function)

The advantage of using JSON is:

It is much lighter than XML and does not have so many redundant things.

JSON is also very readable, but is usually returned compressed. Unlike XML, which can be displayed directly by browsers, browsers need to use some plug-ins to format JSON.

Handling JSON in JavaScript is easy.

Other languages ​​such as PHP also have good support for JSON.

JSON also has some disadvantages:

JSON's server-side language support is not as extensive as XML, but JSON.org provides libraries for many languages.

If you use eval() to parse, security issues may easily arise.

Despite this, the advantages of JSON are still obvious. It is an ideal data format for Ajax data interaction.

Main Tip:

JSONP is a powerful technology for building mashups, but unfortunately, it is not a panacea for all cross-domain communication needs. It has some flaws, which must be carefully considered before committing resources to development.

First, and most importantly, there is no error handling for JSONP calls. If the dynamic script insertion is valid, the call is executed; if it is invalid, it fails silently. There is no prompt for failure. For example, 404 errors cannot be caught from the server, and requests cannot be canceled or restarted. However, if there is no response after waiting for a while, ignore it. (Future versions of jQuery may have features to terminate JSONP requests).

Another major drawback of JSONP is that it can be dangerous when used by untrusted services. Because the JSONP service returns a JSON response wrapped in a function call that is executed by the browser, it makes the host web application more vulnerable to a variety of attacks. If you plan to use a JSONP service, it's important to understand the threats it can pose.

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

Related articles:

Realize mobile phone positioning based on h5 ajax

Use the H5 feature FormData to upload files without refreshing

A detailed explanation of the use of various AJAX methods

The above is the detailed content of AJAX cross-domain request JSONP to obtain JSON data. 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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools