当前位置:网站首页>Cross domain and jsonp

Cross domain and jsonp

2022-06-24 00:54:00 51CTO

1. Understand homology strategy and cross domain

1.1 The same-origin policy

1. What is homology

If two pages of the protocol , Domain name and port are the same , The two pages have the same source .

2. What is homology strategy

Homology policy is a security function provided by the browser

Generally speaking, the browser rules A Website JavaScript Not allowed with non homologous sites C Resource interaction between .

1. Can't read non homologous pages Cookie、LocalStorage and IndexedDB

2. It is impossible to contact non homologous networks DOM

3. Can't send... To a non homologous address Ajax request

1.2 Cross domain

1. What is cross-domain

There are two homologous values URL The agreement 、 The domain name and port are consistent , conversely 、 It's cross domain

The root cause of cross domain : The browser's homology policy does not allow non homology URL Interact with resources .

2. Browser interception of cross domain requests

 Cross domain and JSONP_json

Be careful : The browser allows cross domain requests , however , Data returned from cross domain requests , Will be blocked by the browser , Unable to get... By the page !

3. How to implement cross domain data requests

Today, , Implement cross domain data requests , The two main schemes , Namely JSONP and CORS.

JSONP: It's early , Compatibility is good. , It's the front-end programmer to solve cross domain problems , Forced to come up with a temporary solution . The disadvantage is that it only supports GET request , I won't support it POST request .

CORS: Late appearance , He is W3C standard , Cross domain Ajax The underlying solution to the request . Support GET and POST request , The disadvantage is that it is not compatible with some lower versions of browsers .

2.JSONP

2.1 What is? JSONP

JSONP yes JSON A kind of “ Usage mode ”, It can be used to solve the problem of cross-domain data access in major browsers

2.2 JSONP Implementation principle of

Due to the restriction of browser homology strategy , Can't pass... In the web page Ajax Request non homologous interface data . however <script> Tags are not affected by browser homology policy , Can pass src attribute , Request non homologous js Script .

therefore ,JSONP Implementation principle of , It is through <script> Labeled src attribute , Request a cross domain data interface , And in the form of function calls , Receive the data returned from the cross domain interface response .

2.3 Realize a simple JSONP

  Define a success Callback function :

 Cross domain and JSONP_ Search for _02

 

 

  adopt <script> label , Request interface data :

 Cross domain and JSONP_json_03

 

 

 2.4JSONP The shortcomings of

because JSONP It's through <script> Labeled src attribute , To achieve cross domain data acquisition , therefore ,JSONP Only support GET Data request , I won't support it POST request

Be careful :JSONP and Ajax There is no relationship between , Can't take JSONP The way to request data is called Ajax, because JSONP Not used XMLHttpRequest This object

2.5jQuery Medium JSPNP

jQuery Provides $.ajax() function , In addition to initiating real Ajax In addition to data requests , Can also initiate JSONP Data request

 Cross domain and JSONP_jquery_04

 

 

  By default , Use jQuery Sponsored JSONP request , Will automatically carry a callback=jQueryxxx Parameters of ,jQuery Is the name of a randomly generated callback function

2.6 Custom parameter and callback function name

In the use of jQuery launch JSONP When asked , If you want to customize JSONP And the callback function , You can specify... In two ways :

 Cross domain and JSONP_json_05

 

 

 2.7jQuery in JSONP Implementation process

jQuery Medium JSONP, through <script> Labeled src Property to achieve cross domain data access , It's just ,jQuery It adopts dynamic creation and removal <script> Label mode to initiate JSONP Data request

Is initiating JSONP On request , Dynamic direction <header> in append One <script> label

stay JSONP After the request is successful , Dynamic from <heaber> Remove just append In the <script> label

3. Case study - Taobao Search

3.1 What needs to be achieved UI effect

 Cross domain and JSONP_jquery_06

 

      
      
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- Import the basic style of the page -->
<link rel="stylesheet" href="./css/search.css" />
<!-- Import jQuery -->
<script src="./lib/jquery.js"></script>
</head>
<body>
<div class="container">
<!-- Logo -->
<img src="./images/taobao_logo.png" alt="" class="logo" />

<div class="box">
<!-- tab bar -->
<div class="tabs">
<div class="tab-active"> baby </div>
<div> The store </div>
</div>
<!-- Search area ( Search box and search button ) -->
<div class="search-box">
<input type="text" class="ipt" placeholder=" Please enter what you want to search for " /><button class="btnSearch">
Search for
</button>
</div>
</div>
</div>
</body>
</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

 3.2 Get the search keywords entered by the user

In order to get what the user has entered each time he presses the keyboard , Need to listen to the input box keyup event , The sample code is as follows

 Cross domain and JSONP_json_07

 

 

 3.3 encapsulation getSuggestList function

The code that will get the list of search suggestions , Package to getSuggestList Function , The code structure is as follows

      
      
function getSuggestList(kw) {
$.ajax({
url: 'https://suggest.taobao.com/sug?q=' + kw,
dataType: 'jsonp',
success: function (res) {
console.log(res);
}
})
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

3.4 Rendering suggestion list UI structure

1. Define a list of search suggestions

 Cross domain and JSONP_json_08

 

 

 2. Define template structure

 Cross domain and JSONP_jquery_09

 

 

 3. Functions that define the render template structure

 Cross domain and JSONP_jquery_10

 

 

 4. Hide the list of search suggestions when the search keyword is empty

 Cross domain and JSONP_jquery_11

 

 

 3.5 Anti shake of input box

1. What is anti shake

Anti shake strategy (debounce) When the event is triggered , Delay n Seconds later, the callback , If in this n The second event is triggered again , Then the time will be counted again

2. Application scenario of anti shake

When the user continuously enters a string of characters in the input box , You can use the anti shake strategy , Only after the input is completed , To execute the query request , This can effectively reduce the number of requests , Saving resource ;

3. Achieve input box anti shake

 Cross domain and JSONP_ Search for _12

 

 

 3.6 List of suggestions for cache search

1. Define global cache objects

 Cross domain and JSONP_jquery_13

 

 2. Save search results to cache objects

 Cross domain and JSONP_json_14

 

 3. Get search suggestions from the cache first

 Cross domain and JSONP_ Search for _15

Case code

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

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- Import the basic style of the page -->
<link rel="stylesheet" href="./css/search.css" />
<!-- Import jQuery -->
<script src="./lib/jquery.js"></script>
<script src="/lib/template-web.js"></script>
</head>

<body>
<div class="container">
<!-- Logo -->
<img src="./images/taobao_logo.png" alt="" class="logo" />

<div class="box">
<!-- tab bar -->
<div class="tabs">
<div class="tab-active"> baby </div>
<div> The store </div>
</div>
<!-- Search area ( Search box and search button ) -->
<div class="search-box">
<input type="text" id="ipt" class="ipt" placeholder=" Please enter what you want to search for " /><button class="btnSearch">
Search for
</button>
</div>
<!-- Search suggestion list -->
<div id="suggest-list">

</div>
</div>
</div>
<!-- Template engine structure -->
<script type="text/html" id="tpl-suggestList">
{{each result}}
<!-- Search suggestions -->
<div class="suggest-item">{{$value[0]}}</div>
{{/each}}
</script>

<script>
$(function () {
// 1. Defines the of the delayer ID
let timer = null
// Define global cache objects
let cacheObj = {}

// 2. Define the anti shake function
function debounceSearch(kw) {
timer = setTimeout(function () {
getSuggestList(kw);
}, 500)
}

// Bind... To the input box keyup event
$('#ipt').on('keyup', function () {
// 3. Empty timer
let keywords = $(this).val().trim();
if (keywords.length <= 0) {
return $("#suggest-list").empty().hide()
}

// First determine whether there is data in the cache
if (cacheObj[keywords]) {
return renderSiggestList(cacheObj[keywords])
}

// TODO: Get a list of search suggestions
// console.log(keywords);
// getSuggestList(keywords);
debounceSearch(keywords)
})

function getSuggestList(kw) {
$.ajax({
url: 'https://suggest.taobao.com/sug?q=' + kw,
dataType: 'jsonp',
success: function (res) {
// console.log(res);
renderSiggestList(res)
}
})
}

// Rendering UI structure
function renderSiggestList(res) {
if (res.length <= 0) {
return $('#suggest-list').empty().hide()
}
let htmlStr = template('tpl-suggestList', res)
$('#suggest-list').html(htmlStr).show()

// 1. Get the content entered by the user , As a key
let k = $('#ipt').val().trim()
// 2. You need to cache the data as a value
cacheObj[k] = res
}
})
</script>
</body>

</html>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.

4. Anti shake and throttling

4.1 Throttling strategy (throttle), It's called Siyi , It can reduce the trigger frequency of events over a period of time .

4.2 Application scenarios of throttling

1. When the mouse continuously triggers an event , Trigger only once per unit time

2. Listen and calculate the position of the scroll bar when lazy loading , But you don't have to trigger every slide , It can reduce the frequency of calculation , Without having to waste CPU resources

4.3 Throttling cases - Mouse follow effect

1. Rendering UI Structure and beautify style

 Cross domain and JSONP_jquery_16

 

 2. Achieve mouse following effect when throttling is not used

 Cross domain and JSONP_jquery_17

 

 3. Concept of throttle valve

 Cross domain and JSONP_jquery_18

 

  Throttle valve is empty , Indicates that the next operation can be performed ; Not empty , Indicates that the next operation cannot be performed

The current operation has been executed , The throttle must be reset to empty , Indicates that the next operation can be performed

Before each operation , You must first judge whether the throttle valve is empty .

4. Use throttling to optimize the mouse following effect

  Cross domain and JSONP_json_19

 

 4.4 The difference between anti shake and throttling

Shake proof : If the event is triggered frequently , Anti shake can only ensure that only one trigger takes effect , front N Multiple triggers are ignored

throttle : If the event is triggered frequently , Throttling can reduce the frequency of event triggering , therefore , Throttling is the selective execution of some events

 


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240033120694.html