Ajax Advanced Chapter 02—Cross-domain and JSONP

PrefaceNo matter how bumpy the road ahead is, as long as you go in the right direction, you are closer to happiness than standing still.

Ajax Advanced Chapter 02—Cross-domain and JSONP

1. Ajax Advanced Chapter 02—Cross-domain and JSONP

(1) Same origin strategy

1.1 What is homology

If two pagesprotocoldomain nameandportare the same, then both pages have the same source.

For example, the following table shows the same origin detection relative to the page http://www.test.com/index.html:

URLIs it homologous?reason
http://www.test.com/other.htmlyesSame origin (same protocol, domain name, and port)
https://www.test.com/about.htmlnoDifferent protocols (http vs. https)
http://blog.test.com/movie.htmlnoDifferent domain names (www.test.com and blog.test.com)
http://www.test.com:7001/home.htmlnoThe ports are different (default port 80 and port 7001)
http://www.test.com:80/main.htmlyesSame origin (same protocol, domain name, and port)

1.2 What is the same-origin policy?

1️⃣ Same origin policy(English full name Same origin policy) is a security feature provided by the browser;

The concept given by MDN official: The same-origin policy restricts how documents or scripts loaded from the same source interact with resources from another source. This is an important security mechanism for isolating potentially malicious files;

Popular understanding: The browser stipulates that the JavaScript of website A does not allow resource interaction with website C that is not of the same origin, such as:

  1. Unable to read Cookie, LocalStorage and IndexedDB of non-original web pages;
  2. Unable to access the DOM of non-original web pages;
  3. Unable to send Ajax requests to non-original addresses;

(2) Cross-domain

2.1 What is cross-domain

Homology means that the protocol, domain name, and port of the two URLs are the same; otherwise, they are cross-domain.

The root cause of cross-domain occurrence:The browser’s same-origin policy does not allow resource interaction between non-original URLs;

2.2 Browser interception of cross-domain requests

Warm reminder: Browsers allow cross-domain requests, but the data returned by cross-domain requests will be intercepted by the browser and cannot be obtained by the page!

2.3 How to implement cross-domain data requests

Nowadays, the two most important solutions to implement cross-domain data requests are:JSONPandCORS

2️⃣ JSONP: It appeared early and has good compatibility (compatible with lower versions of IE). It is a temporary solution that front-end programmers are forced to come up with in order to solve cross-domain problems. The disadvantage is that it only supports GET requests and does not support POST requests;

3️⃣ CORS: Appeared later, it is a W3C standard and is the fundamental solution for cross-domain Ajax requests. Supports GET and POST requests. The disadvantage is that it is not compatible with some lower version browsers;


3.1 What is JSONP

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

3.2 Implementation principles of JSONP

Due to the restriction of the browser’s same-origin policy, non-original interface data cannot be requested through Ajax in web pages. but<script>The tag is not affected by the browser’s same-origin policy, and you can request non-original js scripts through the src attribute.

Therefore, the implementation principle of JSONP ispass<script>The src attribute of the tag requests the cross-domain data interface, and receives the data returned by the cross-domain interface response in the form of a function call.

3.3 Disadvantages of JSONP

Since JSONP is passed<script>The src attribute of the tag is used to obtain cross-domain data, so,JSONP only supports GET data requests and does not support POST requests.

Reminder:There is no relationship between JSONP and Ajax, the way JSONP requests data cannot be called Ajax, because JSONP does not use the XMLHttpRequest object.

3.4 JSONP in jQuery

The $.ajax() function provided by jQuery can not only initiate real Ajax data requests, but also initiate JSONP data requests. The code demonstration is as follows:

	url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
    // If you want to use $.ajax() to initiate a JSONP request, you must specify the datatype as jsonp
    dataType: 'jsonp',
    success: function(res) {

Warm reminder: By default, using jQuery to initiate a JSONP request will automatically carry acallback=jQueryxxxParameters, jQueryxxx is a randomly generated callback function name.

3.5 Custom parameters and callback function names

When using jQuery to initiate a JSONP request, if you want to customize the JSONP parameters and callback function name, you can specify them through the following two parameters:

    url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
    dataType: 'jsonp',
    //The parameter name sent to the server, the default value is callback
    jsonp: 'callback',
    // Customized callback function name, the default value is jQueryxxx format
    jsonpCallback: 'abc',
    success: function(res) {

3.6 Implementation process of JSONP in jQuery

JSONP in jQuery is also passed<script>The src attribute of the tag implements cross-domain data access, but jQuery usesDynamic creation and removal <script>Tags are used to initiate JSONP data requests.

  • When initiating a JSONP request, dynamically<header> middle append one<script>Label;
  • After the JSONP request is successful, dynamically from<header>Remove what was appended just now<script>Label;

(4) Anti-shake

4.1 What is anti-shake?

The debounce strategy (debounce) is when an event is triggered,delay n secondsLaterExecute callback,ifThe event is triggered again within these n seconds,butReclock

4.2 Application scenarios of anti-shake

When the user continuously inputs a string of characters in the input box, the anti-shake strategy can be used to execute the query request only after the input is completed. This can effectively reduce the number of requests and save request resources;

To achieve anti-shake of input box:

var timer = null; // 1. Anti-shake timer

function debounceSearch(keywords) { // 2. Define the anti-shake function
	timer = setTimeout(function() {
    // Initiate JSONP request
    }, 500)

$('#ipt').on('keyup', function() { // 3. When the keyup event is triggered, clear the timer immediately
    // ...Omit other code

(5) Throttling

5.1 What is throttling

Throttling means that events are triggered continuously but the function is only executed once in n seconds. Throttling dilutes the frequency of function execution;

5.2 Application scenarios of throttling

  1. The mouse continuously triggers an event (such as click), and only triggers it once per unit time;
  2. When lazy loading, it is necessary to monitor and calculate the position of the scroll bar, but it does not need to be triggered every time it is slid, which can reduce the frequency of calculation without wasting CPU resources;

5.3 Concept of throttle valve

throttle valveIs empty,expressCan perform next operationnot null,expressCannot perform next operation
After the current operation is completed, the throttle valve must be reset to empty, indicating that the next operation can be performed;
Before each operation,It must first be determined whether the throttle valve is empty

5.3 Throttling case – mouse following effect

Case material:

The complete code demonstration is as follows:

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./lib/jquery.js"></script>
        /* CSS style*/
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;

        #angel {
            position: absolute;

    <! -- UI Structure -->
    <img src="./angel.gif" alt="" id="angel" />

        $(function () {
            // 1. Get the picture
            var angel = $('#angel')
            // Step 1. Define the throttle valve
            var timer = null;
            // 2. Bind mousemove event
            $(document).on('mousemove', function (e) {
                // Step 3: Determine whether the throttle valve is empty. If it is not empty, it proves that the interval from the last execution is less than 16 milliseconds.
                if (timer) { return }
                // 3. Set the position of the image
                // Step 2: Turn on the delayer
                timer = setTimeout(function () {
                    $(angel).css('top', e.pageY + 'px').css('left', e.pageX + 'px')
                    //When the mouse following effect is set, clear the timer throttle so that the delay can be turned on next time
                    timer = null
                }, 16)


(6) Summarize the difference between anti-shake and throttling

  • Anti-shake: If the event is triggered frequently, anti-shake can ensureOnly the last trigger takes effect, the previous N multiple triggers will be ignored;
  • Throttling: If an event is triggered frequently, throttling canReduce the frequency of event triggers,Therefore, throttling is the selective execution of a ,portion of events;

2. Summary

😝 Since there is a lot of content, I decided to write it separately. I will keep updating it! Friends who like it, remember to like it! 😝

Related Posts

Multi-threaded learning

Forest detailed introduction

[001] [ESP32 Development Notes] IDF project creation and CMake configuration

vue3+vite+typescript implements low-code form editor

I have painstakingly compiled a comprehensive collection of JavaScript knowledge points, with super detailed suggestions for collection! ! !

Node.js implements WebSocket


HTML rotating photo album (0 basics, learn in 1 minute)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>