jquery jsonp is to use the src
attribute in the script
tag to solve the cross-domain problems encountered in front-end and back-end data requests. One thing I don’t understand is that jquery dynamically generates The script
tag is appended to the head
tag, which is the head of the document; generally our callback function is in body
, the function is declared first and then used, without declaration Why can we get the data passed from the background even if we call it directly?
The following is a test I did:
//同源策略下有两个文件:a.html和b.js.
//a.html中的内容为:
//<script type="text/javascript" src="b.js"></script>
function test(val){
console.log(val)
}
//<script type="text/javascript" src="b.js"></script>
//b.js的内容为:
test(10)
If this string of code is placed below the declared test
function, the number 10 will be printed. If it is placed above the test
function, an error will be reported
ReferenceError: test is not defined
Comparing the implementation of jquery, I don’t quite understand why the dynamically generated js will be executed if it is called before the declared function?
If it is a directly linked src, the browser parses it from top to bottom, and will retrieve the value in b.js first. The function of a.js has not yet been loaded into the page, and there is no test( ) this function, so an error will be reported
But when sending an ajax request, you wait for the page to be completed before requesting it. That is, you first declare a callback function and then create a script to request, so the location of the script at this time will not affect the final result. .
Because you ignored the asynchronous problem, in terms of execution order, when the script tag sent back from the server is loaded, your local callback function must have been defined, so you can call the corresponding method.
Simply put:
jsonp=Define local callback function=>Load script tag=>Run the content of the loaded script tag.
jsonp To put it bluntly, it is an agreement:
'We are too far apart and can't reach each other, how can you give me your things?'
'How about I throw it to you, can you catch it?'
'Okay, I have a basket (callback), which is at your 1 o'clock position (callbackName), you throw it there. As for whether the basket exists or not, and whether it is in the right position, it does not affect your agreement.
The js loading location introduced by jsonp is the location where the jsonp statement to obtain js is executed. As for the placement, it's just a formality.