Home  >  Article  >  Web Front-end  >  Detailed explanation of jsonp and post of jQuery.ajax()

Detailed explanation of jsonp and post of jQuery.ajax()

小云云
小云云Original
2018-01-06 09:19:132297browse

I used to think that when the dataType of $.ajax() is set to jsonp, its method (request method) will become get no matter how it is set, until I encountered a pit two days ago. This article mainly introduces the relevant information about jQuery.ajax()'s jsonp and post. The article introduces it in detail through the example code, which has certain reference and learning value for everyone. Friends who need it can take a look below.

About cross-domain requests and jsonp

  • Cross-domain: Due to the impact of the same-origin policy (the protocol, domain name, and port must all be the same), the ajax request will Being restricted, to break through this restriction, cross-domain is born. There are many cross-domain solutions. I will not elaborate here. I will just explain the jsonp cross-domain solution in the GET request.

  • jsonp, essentially jsonp is not an xhr asynchronous request, but a js file is requested, so the cross-domain request of jsonp cannot be seen under the xhr tag in the network panel of chrome. You can see it under the js tag. It is to use the src in the script tag to not be restricted by the same-origin policy. The front-end defines a callback function, obtains the data in the requested js script, and executes the front-end callback function. Therefore, the front-end and back-end need to define the callback function name uniformly.

  • jsonp in $.ajax, $.ajax encapsulates jsonp and looks like an ajax request. Since jsonp is a cross-domain solution for get requests, previous experience tells me that even if the type is set to post, it will be automatically converted to get when using jsonp, until one day I step on a trap. Looking through the source code of the $.ajax module, I found that only when crossDomain is manually set to true, or is it actually cross-domain, will it be set to get. Otherwise, still fill in the type


#Conclusion:

Manually set crossDomain is true, or it is really cross-domain, the type will be modified to GET, otherwise the type parameter will still be passed in.

Related recommendations:

Detailed explanation based on JSONP principle

Principles of Jsonp and simple implementation methods

Principles of jsonp, introduction to methods of encapsulating jsonp

The above is the detailed content of Detailed explanation of jsonp and post of jQuery.ajax(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn