JSONP cross-domain simulation Baidu search

JSONP cross-domain simulation Baidu search

1. What is JSONP

JSONP is short for JSON with padding padding, which is a new way to apply JSON. It is very popular in later Web services. JSONP looks similar to JSON, but it is JSON contained in a function call, like this:

callback({"name": "王欢"});

SONP consists of two parts : callback function and data. The callback function is the function that should be called in the page when the response comes. The name of the callback function is usually specified in the request. The data is the JSON data passed into the callback function. The following is a typical JSONP request.

https://freegeoip.net/json/?callback=handleResponse

This URL is requesting a JSONP geolocation service. It is common to specify the callback parameters of the JSONP service through the query string, as shown in the URL above. The name of the callback function specified here is: handleResponse()
JSONP is used through the dynamic <script> element, and a cross-domain URL can be specified for the src attribute. You can load resources from other domains without restriction. Because JSONP is valid JavaScript code, it will be executed immediately after the request is completed, that is, after the JSONP response is loaded into the page.

2. JSONP cross-domain request

We know that the same-origin policy is a security mechanism of the browser. The so-called source refers to the protocol, domain name and port number. When our script is running, the browser will detect whether the script it executes and the data it obtains are the same as our HTML page. If they are the same, they are of the same origin and a successful request will be made. If their sources are different, it is a cross-domain request. By default, browsers do not support cross-domain requests. So what should we do if we want to make a cross-domain request?
script tag is not restricted by the same-origin policy, that is, when we request a script, it can be requested no matter it is on the server where the HTML is located or on other servers, so we use this property of script tag to make cross-domain requests for data. Let's take a look at how JSONP performs cross-domain requests.
First, we request a script code. If it can call a function we specify and pass the data as an actual parameter, then as long as we define this function and define the formal parameter, the formal parameter will receive its actual parameter to get the data. For example:
Suppose a getData(data) is defined in the script. If a script is requested now, the script can call the getData() function and pass data as the actual parameter. The data received by the formal parameter can then be processed accordingly.

<script>
        function getData(data){
            console.log(data);
        }
        var script = document.createElement('script');
        script.id = 'jsonp';
        script.src = 'jsonp.js';
        document.body.appendChild(script);
    </script>

Assuming that the front-end has told the back-end the function name, the back-end can call getData() and pass the information. In jsonp.html , you can request the following jsonp.js file.

getData({
    name: 'Xiao Wang',
    age: 20
})

The result of running is:

We get an Object object, which is the data we passed.
So, how do we tell the server to use the getData() function? If we always use getData(), our development will be very rigid and we won’t be able to define other function names. In fact, we can use the get request to tell the backend the name of the function defined by our frontend through parameters, and the backend will dynamically generate such a script file and return it to the function call.
Baidu has such an interface, let’s take a look at it.
Open the Baidu page in the browser, open the debugging tool, and look under NETwork label to monitor all http requests sent by the browser to the server and view the data.

Type "b" in the search box, and the request will be as shown below:

The requested keywords are:

insert image description here

The callback function here is actually a global function generated by jQuery. After getting this URL , we can save its useful information and replace the callback function with another function:

https://www.baidu.com/sugrec?pre=1&wd=b&req=2&csor=1&cb=getData();


Test it by typing this into the address bar:

It can be found that this callback function becomes the one we set.

3. Simulate Baidu search

We can now use this interface to generate JSON to simulate the Baidu search page.
We define a global variable as a function to receive data, data is the received data, once getdata() function is called, it means that our Jsonp function has been sent, at this time we can delete the script tag through removeChild() , so that every time we send a request, script tag will be deleted after receiving the data, when processing the data, getData() returns us an object with a keyword g, which corresponds to an array containing strings. We first traverse this array, and then generate a li according to each element and add it to the ul under the input, first clear the html in the ul, in this way, each requested li is brand new, when keyup comes out, first get the current input value and call getdata() function, pass wd in, and the jsonp data transmission process is realized.

The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: relative;
            width: 600px;
            height: 40px;
        }
        input {
            width: 500px;
            height: 40px;
            border: 2px solid #4E6EF2;
        }
        button{
            position: absolute;
            left: 411px;
            top: 0;
            width: 95px;
            height: 44px;
            background-color: #4E6EF2;
            border: none;
            font-size: 18px;
            color: white;
        }
        ul{
            position: relative;
            left: -40px;
            top: -10px;
            width: 411px;
            height: 400px;
            
        }
        li{
            height: 40px;
            width: 411px;
            line-height: 40px;
            font-size: 16px;
            list-style: none;

        }
    </style>
</head>
<body>
   <div>
    <input type="text" value =''>
    <button>Search on Baidu</button>
   </div>
    <ul></ul>
    <script src="jquery.js"></script>
    <script>
     //
        function getData(data){
            var script = document.querySelector('#jsonp');
            script.parentNode.removeChild(script);
            $('ul').html('');
            for(var i =0;i<data.g.length;i++){
                $('<li>'+data.g[i].q +'</li>').appendTo('ul');
            }
        }
        //Dynamically generate script function getList(wd){
            var script = document.createElement('script');
            script.id = 'jsonp';
            script.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=26350&req=2&csor=1&cb=getData&wd='+wd;
           
            document.body.appendChild(script);
        }
  //var ipt = document.querySelector('input');
        ipt.addEventListener('keyup',function(){
            var wd = this.value;
            getList(wd);
            console.log(wd);
        })
    </script>
</body>
</html>

The effect is:

JSONP Disadvantages

JSONP is extremely popular among developers because it is very simple and easy to use, but it also has two disadvantages:

  • First, JSONP is about loading executable code from another domain. If the other domain is not secure, it is likely that some malicious code will be included in the response. At this time, there is no way to investigate except to completely abandon the JSONP call.
  • 其次,要確定JSONP請求是否失敗并不容易。雖然HTML5給the <script> element, it is not yet supported by any browser. To do this, developers have to use a timer to detect whether a response is received within a specified time. But after all, not every user has the same Internet speed and bandwidth, so the operation is not satisfactory.

This is the end of this article about JSONP cross-domain simulation Baidu search. For more relevant JSONP cross-domain simulation Baidu search content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • In-depth analysis of homology and cross-domain, jsonp (function encapsulation), CORS principle
  • Implementation of JSONP to solve JS cross-domain problem
  • Analysis of the Principle of Jsonp Cross-Domain Solution
  • jQuery uses jsonp to implement Baidu search sample code
  • Baidu search box smart prompt case jsonp

<<:  Share 8 very useful CSS development tools

>>:  Introduction to Docker Quick Deployment of SpringBoot Project

Recommend

Practical solution for Prometheus container deployment

environment Hostname IP address Serve Prometheus ...

Detailed explanation of the fish school algorithm in CocosCreator game

Preface I recently wanted to learn CocosCreator, ...

JavaScript to implement the back to top button

This article shares the specific code for JavaScr...

Implementation of react automatic construction routing

Table of contents sequence 1. Centralized routing...

An example of vertical centering of sub-elements in div using Flex layout

1. Flex is the abbreviation of Flexible Box, whic...

Javascript uses the integrity attribute for security verification

Table of contents 1. Import files using script ta...

Summary of two methods to implement vue printing function

Method 1: Install the plugin via npm 1. Install n...

jQuery implements nested tab function

This article example shares the specific code of ...

Design and implementation of Vue cascading drop-down box

Table of contents 1. Database design 2. Front-end...

Solution to the Chinese garbled characters problem in MySQL under Ubuntu

Find the problem I have been learning Django rece...

js realizes a gradually increasing digital animation

Table of contents background Achieve a similar ef...

MySQL 8.0.15 version installation tutorial connect to Navicat.list

The pitfalls 1. Many tutorials on the Internet wr...

IE conditional comments for XHTML

<br />Conditional comments are a feature uni...