search
HomeWeb Front-endJS TutorialjQuery's JSONP Explained with Examples

jQuery's JSONP Explained with Examples

Summary of key points

  • JSONP (JSON with padding) allows cross-domain Ajax calls, circumventing homologous policies that restrict scripts from accessing data from different sources. This is done by having the server return JSON data containing the function call, which the browser can interpret.
  • While JSONP is valuable for getting data from different sources and accessing content for various services, it also has some limitations. JSONP can only perform cross-domain GET requests and must be explicitly supported by the server. It also has potential security issues as it opens up possibilities for cross-site scripting (XSS) attacks.
  • Other solutions to homologous policies include the use of proxy or the implementation of cross-origin resource sharing (CORS). The proxy allows server-side code to perform cross-origin requests, while CORS allows browsers to communicate across domains by including a new Access-Control-Allow-Origin HTTP header in the response. However, each method has its own shortcomings and limitations.

This article was updated on June 23, 2016 to address quality issues. Comments related to old articles have been deleted. If you are developing a web-based application and trying to load data from a domain that is not under your control, you are likely to see the following message in the browser's console: XMLHttpRequest cannot load https://www.php .cn/link/0df0dbfc4725c2259dc0bb045e9bf6d2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.php.cn/link/28db3b5e7bfadf38b792da7192530ac1' is therefore not allowed access.

In this article, we will explore what causes this error and how to solve this problem by using jQuery and JSONP.

Same Origin Policy

General web pages can use XMLHttpRequest objects to send and receive data to remote servers, but the same-origin policy limits what they can perform. This is an important concept in the browser security model, which stipulates that web browsers may only allow scripts on page A to access data on page B if both pages have the same source. The source of the page is defined by its protocols , host and port number . For example, the source of this page is "https", "www.sitepoint.com", "80". Homogen policy is a security mechanism. It prevents scripts from reading data from your domain and sending it to their servers. Without this, it's easy for a malicious website to crawl your session information to another site (such as Gmail or Twitter) and perform actions on your behalf. Unfortunately, it also causes the errors we see above and often causes trouble for developers trying to complete legitimate tasks.

Example of failure

Let's see what doesn't work. This is a JSON file located on a different domain and we want to load it using jQuery's getJSON method.

$.getJSON(
  "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
  function(json) { console.log(json); }
);

If you open the console in your browser and try it out, you will see a message similar to the one mentioned above. So what can we do?

Possible Solutions

Luckily, not everything is affected by homologous policies. For example, it is entirely possible to load an image or script into your page from a different domain - you are doing this when you include jQuery from a CDN (for example). This means we can create a <script></script> tag, set its src attribute to our JSON file, and inject it into the page.

var script = $("<script>", {
    src: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
    type: "application/json"
  }
);

$("head").append(script);

While this works, it doesn't help us much, because we can't access the data it contains.

Beginner of JSONP

JSONP (on behalf of JSON with padding) is based on this technique and provides us with a way to access the returned data. It is implemented by having the server return JSON data containing a function call ("popular") which the browser can then interpret. This function must be defined in the page that evaluates the JSONP response.

Let's see what the previous example looks like. This is an updated JSON file that wraps the original JSON data in a jsonCallback function.

function jsonCallback(json){
  console.log(json);
}

$.ajax({
  url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
  dataType: "jsonp"
});

This records the expected results to the console. We now have (although fairly limited) cross-domain Ajax.

Third-party API

Some third-party APIs allow you to specify the name of a callback function that should be executed when the request returns. One such API is the GitHub API.

In the following example, we get the user information of John Resig (jQuery creator) and log the response to the console using the logResults callback function.

function logResults(json){
  console.log(json);
}

$.ajax({
  url: "https://api.github.com/users/jeresig",
  dataType: "jsonp",
  jsonpCallback: "logResults"
});

This can also be written as:

$.getJSON("https://api.github.com/users/jeresig?callback=?",function(json){
  console.log(json);
});

The ? at the end of the URL tells jQuery that it is processing a JSONP request instead of JSON. jQuery then automatically registers the callback function, which it calls when the request returns.

If you want to learn more about jQuery's getJSON method, please check out: Ajax/jQuery.getJSON Simple Example

Precautions

But as you may have realized by now, this approach has some drawbacks.

For example, JSONP can only perform cross-domain GET requests, and the server must explicitly support it. JSONP is not without security issues, so let's briefly introduce some other solutions.

Using agent

The server-side code is not subject to the same-origin policy and can execute cross-origin requests without any problem. So you can create some kind of proxy and use it to retrieve any data you need. Refer to our first example:

/* proxy.php */
$url = "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;

In the client:

$.getJSON("https://www.php.cn/link/28db3b5e7bfadf38b792da7192530ac1.com/proxy.php", function(json) {
  console.log(json);
})

But this method also has its disadvantages. For example, if a third-party site uses cookies for authentication, this method will not work.

CORS

Cross-origin Resource Sharing (CORS) is a W3C specification that allows browsers to communicate across domains. This is done by including the new Access-Control-Allow-Origin HTTP header in the response.

Referring to our first example, you can add the following to the .htaccess file (assuming Apache) to allow requests from different sources:

$.getJSON(
  "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
  function(json) { console.log(json); }
);

(If you are running a server that is not Apache, please check it out here: https://www.php.cn/link/819e2e55be8ef0957b56ea94356bfb79)

You can learn more about CORS in one of our recent tutorials: Learn more about CORS

Conclusion

JSONP allows you to bypass homologous policies and to some extent make cross-domain Ajax calls. It is not a magic pill, and of course it has its problems, but in some cases it can prove invaluable when data is taken from different sources.

JSONP also allows you to extract a variety of content from different services. Many well-known websites offer JSONP services (such as Flickr) that allow you to access their content through predefined APIs. You can find a complete list of them in the ProgrammableWeb API directory.

(The following is the FAQ part, which has been adjusted and simplified according to the original text to avoid duplicate information)

FAQs about JSONP (FAQ)

  • What is the main difference between JSON and JSONP? Both JSON and JSONP are formats used to process data between servers and web applications. The main difference is how they handle cross-domain requests. JSON cannot support cross-domain requests due to homologous policies (security measures implemented in Web browsers). On the other hand, JSONP bypasses this policy by using a populating method, allowing data to be requested from servers with different domains than the client.

  • How does JSONP bypass the same-origin policy? JSONP bypasses homologous policies by using the padding or "Fill Request" method. In this method, the client requests data from servers in different domains by appending the callback function to the URL. The server then wraps the requested data in this function and sends it back to the client. The client executes this function to access the data. This method allows JSONP to overcome the cross-domain limitations imposed by homologous policies.

  • Is JSONP safe? Although JSONP provides a solution for homologous policies, it does have its own security risks. Because JSONP involves executing scripts received from the server, if the server is corrupted, it opens up the possibility for a cross-site scripting (XSS) attack. Therefore, be sure to use JSONP only with trusted sources.

  • Can JSONP handle error responses? Unlike JSON, JSONP does not have built-in error handling. If the JSONP request fails, the browser does not throw an error and the callback function is not executed. To handle errors in JSONP, you can implement a timeout mechanism that triggers an error if the callback function is not executed within a specified time.

  • How to make a JSONP request using jQuery? jQuery provides an easy way to make JSONP requests using the $.ajax() method. You need to specify dataType as "jsonp" in the $.ajax() setting.

  • What are the limitations of JSONP? JSONP has some limitations. It only supports GET requests and does not support POST or other HTTP methods. It also lacks error handling capabilities. Additionally, JSONP poses security risks due to its approach to bypassing homologous policies.

  • Is JSONP still used now? Although JSONP was a popular solution for cross-domain requests in the past, CORS now has a low frequency of use due to the emergence of CORS (cross-origin resource sharing), CORS provides a safer and more powerful cross-domain requests. method.

The above is the detailed content of jQuery's JSONP Explained with Examples. 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
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.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)