Why jsonp can only use get requests? Is it because of some reasons of get, some reasons of post, or some other reasons? I checked the document and it said that 'this is determined by the characteristics of the technology itself'. What does this characteristic mean? Can you explain it in detail? Many thanks!
JSONP is a
【request a JS script and use the result of executing this script as data】
method.
So, can you POST a script introduced through the script tag?
(If you have read the source code of the JSONP library, you will know that the common implementation code is actually
document.createElement('script')
to generate a script tag and then insert it into the body. There is no room to set the request format here).The JS code in domain name A AJAX requests server data with domain name B. This is a cross-domain AJAX request, which is not possible by default.
But there are places in HTML where cross-domain requests can be made, such as img script tags. Their src attributes point to addresses that are not under domain name A (that is, cross-domain).
Then someone took advantage of the above characteristics, chose the feature of src in script that can obtain content across domains, and developed a hack protocol like JSONP. (Requests in src are all GET)
That assumes the JSONP request is as follows:
What’s going on behind the scenes:
Splice a script tag,
<script src="http://path/to/server/b?A=a&B=b&callbackFunctionName=myCallback"></script>
, thereby triggering a GET to the specified address RequestThe server processes this GET request and returns the string "myCallback('response value')"
After the front-end script is loaded, it is actually executed in the script
myCallback('response value')
Have the cross-domain request been completed?
Is it just possible to use GET
Similar to dynamically adding a js code to your page, do you think the js file can be posted?
Suppose the address you requested returns a web page like this.
The browser needs to parse this webpage after getting it, and parse it to
When I read this line of code, I knew that a js file was needed here, so I initiated another request to get this js file. This request can only use the GET method, not POST, just like you enter the address in the browser address bar. It’s the same as pressing Enter to enter.
The implementation principle of JSONP is to create a script tag, and then put the api address that needs to be requested in src. So it can only be GET.
Because of the <script> tag, only GET is supported