Home > Web Front-end > JS Tutorial > body text

How does JSONP handle Ajax cross-domain access?

php中世界最好的语言
Release: 2018-04-04 14:13:01
Original
1515 people have browsed it

This time I will show you how JSONP handles Ajax cross-domain access. What are the precautions for JSONP to handle Ajax cross-domain access. The following is a practical case, let's take a look.

A few days ago, there was a new requirement at work, which required the front-end web page to asynchronously call the background Webservice method to return information. There are many implementation methods. This example uses jQuery+Ajax. After completion, everything was ok when debugging locally. However, problems occurred after deploying to the server. The background service call did not respond. What happened? The code has not changed much, the only modification is the url address in jQuery's ajax method. Is this the problem here? After inspection and debugging, it was found that the same origin policy was causing trouble. We know that JavaScript or jQuery is a dynamic script technology often used in Web front-end development. In JavaScript, there is a very important security restriction called "Same-Origin Policy". This policy places important restrictions on the page content that JavaScript code can access, that is, JavaScript can only access content under the same domain name as the document or script that contains it. Scripts under different domain names cannot access each other, even in subdomains.

But sometimes cross-domain operations are unavoidable. At this time, the "same origin policy" is a limitation. What should I do? Using JSONP cross-domain GET request is a common solution. Let's take a look at how JSONP cross-domain is implemented and explore the principle of JSONP cross-domain.

JSONP is mentioned here, so someone asked, what are the differences and differences between it and JSON? Let’s take a look. Baidu Encyclopedia has the following explanation:

JSON(JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition - December 1999). JSON uses a completely language-independent text format, but also uses habits similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language. It is easy for people to read and write, and it is also easy for machines to parse and generate (network transmission speed is fast).

JSONP (JSON with Padding) is a "usage mode" of JSON that can be used to solve the problem of cross-domain data access by mainstream browsers. Due to the same-origin policy, generally speaking, web pages located at server1.example.com cannot communicate with servers other than server1.example.com, with the exception of the HTML

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template