The most commonly used jquery + ajax method is $. post, which is a second encapsulation of $. ajax. Next let's take a look at the use of $. ajxa:
The code is as follows: |
Copy code |
$ ('# Ajax'). click (function (){ $. Ajax ({ Type: 'post ', Url: 'Test. Php ', DateType: 'HTML ', // supports htmlxmljsonjsonp Data: {domain: 'www .111cn.net ', keyword: 'php blog '}, Success: function (response, status, xhr ){ Console. log ('success: '+ response ); }, Error: function (response, status, xhr ){ Console. log ('Error: '+ response) } }); });
|
Here, for cross-origin operations on jsonp, refer to the article: php + jquery + jsonp cross-origin ajax implementation
When the form is submitted, there may be a lot of data. In that case, there will be a lot of parameters in data: {} and it is prone to errors, so we will use form serialization serialize ()
The code is as follows: |
Copy code |
$ ('. Btn'). click (function (){ $. Ajax ({ Type: 'post ', Url: 'Test. Php ', DateType: 'json', // supports htmlxmljsonjsonp Data: $ ('form'). serialize (), // success: {"user": "tuisiyuan", "email": "1054770532@qq.com "} // Data: $ ('form'). serializeArray (), // success: {"user": "tuisiyuan", "email": "1054770532@qq.com "} Success: function (response, status, xhr ){ Console. log ('success: '+ response ); }, Error: function (response, status, xhr ){ Console. log ('Error: '+ response) } }); }); |
Screenshot of serialize in php:
Screenshot of serializeArray in php:
From the above, we can see that there is basically no difference between serialize and serializeArray in the processing of data on the php side.
Another less commonly used but useful method is the ajax data initialization method: $. ajaxSetup initializes repeated data.
$. AjaxSetup ({// initialize common data so that the code does not repeat too much
The code is as follows: |
Copy code |
Type: 'post ', Url: 'Test. Php' }); |
Supplement: jsonp implements ajax cross-origin requests
First, load the following code under a local domain name:
The code is as follows: |
Copy code |
<Scripttype = "text/javascript" src = "http://www.lshop.com/js/test.js"> </script> Then I pasted the jsonp code in the js test. js in www.lshop.com: $. Ajax ({ Type: "get ", Async: false, Url: 'http: // www.111cn.net/index. Php ', DataType: "jsonp ", // Jsonp: "callback", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (usually the default value is callback) JsonpCallback: "flightHandler", // The function that needs to wrap the returned data when returning a value in php Success: function (json ){ Alert ('My keywords are: '+ json. stitle ); }, Error: function (){ Alert ('fail '); } }); |
Php code:
The code is as follows: |
Copy code |
$ A = json_encode (array ('title' => 'It blog ', 'stitle' => 'javascript blog ')); Echo "flightHandler ($ )"; Exit; |
The result is: pop-up-my keyword is: javascript blog.