Phpajax data submission post and post common methods

Source: Internet
Author: User
In many cases, ajax is not a problem, but sometimes the problem of incomplete ajax data submission and post is encountered. I hope the article will help you. below is a standard ajax request code. normally there will be no problems,... in many cases, ajax is not a problem, but sometimes the problem of incomplete ajax data submission and post is encountered. I hope the article will help you.

The following is a standard ajax request code. normally, there will be no problems, but there will be problems under specific circumstances, for example, when username = fdas & 321, or the & symbol appears in the parameter value. in order to find this problem, I read the http header information in N multilateral, because the data is transmitted only after one side, however, the printed data is half-cut. Finally, we carefully observe the header information and find that the transmitted header is incorrect. The problem is located on js, this problem occurs when the string is concatenated. username = fdas & 321 & password = password is incorrect. Therefore, we need to convert the transmitted data to the form of {username: username, passsword: password}. the code is as follows:

$(".submit").bind('click', function () {    var username = $("input[name='username']").val();    $.ajax({        url : "post",        type : "post",        dataType : "json",        data : "username=" + username + "&password=" + password,        timeout : 5000,        error : function () {            alert(1)        },        success : function () {}    })})

Four common POST data submission methods

Application/x-www-form-urlencoded

This should be the most common way to submit data through POST. If the native form of the browser does not set the enctype attribute, data will be submitted in the form of application/x-www-form-urlencoded. the request is similar to the following, the unrelated request header is omitted in this article. the code is as follows:

POST http://www.phprm.com HTTP/1.1Content-Type: application/x-www-form-urlencoded;charset=utf-8title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

First, Content-Type is specified as application/x-www-form-urlencoded. Second, the submitted data is encoded in key1 = val1 & key2 = val2, both key and val are URL transcoded. Most server languages support this method. For example, in PHP, $ _ POST ['title'] can get the title value, and $ _ POST ['sub'] can get the sub array.

This method is often used when Ajax is used to submit data. For example, for Ajax of JQuery and QWrap, the default value of Content-Type is "application/x-www-form-urlencoded; charset = utf-8 」.

Multipart/form-data

This is also a common POST data submission method. when we use a form to upload a file, we must make the form's enctyped equal to this value. let's look at a request example. the code is as follows:

POST http://www.phprm.com HTTP/1.1 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA  ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="text"  title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/png PNG ... content of chrome.png ...

------ WebKitFormBoundaryrGKCBY7qhFd3TrwA --

This example is a little complicated. First, a boundary is generated to separate different fields. to avoid duplication with the body content, boundary is very long and complex. Content-Type indicates that the data is encoded by mutipart/form-data. what is the boundary of this request. The message body is divided into similar parts according to the number of fields. each part starts with -- boundary, followed by the content description, followed by the carriage return, finally, the specific content of the field (text or binary ). If a file is transmitted, it also contains the file name and file type information. The message subject ends with the -- boundary -- mark. For detailed definitions of mutipart/form-data, go to rfc1867.

This method is generally used to upload files, and the major server languages also have good support for it.

The two POST data methods mentioned above are both supported by the browser native, and currently the native form only supports these two methods. However, as more and more Web sites, especially webapps, use Ajax for data interaction, we can define new data submission methods to facilitate development.

Application/json

The Content-Type of application/json is the response header. In fact, more and more people use it as the request header to tell the server that the message subject is a serialized JSON string. Due to the popularity of JSON specifications, all major browsers except earlier versions of IE support JSON. stringify native, and the server language also has functions for processing JSON, so there is no trouble in using JSON.

JSON format supports more complex structured data than key-value pairs, which is also useful. I remember that when I was working on a project a few years ago, I had to submit a very deep data hierarchy. I just submitted the data after JSON serialization. However, at that time, I used the JSON string as the val and put it in the key-value pair and submitted it in x-www-form-urlencoded mode.

Google's AngularJS Ajax function submits JSON strings by default. for example, the following code:

var data = {'title':'test', 'sub' : [1,2,3]}; $http.post(url, data).success(function(result) {     ... });

The final request is:

POST http://www.phprm.com HTTP/1.1Content-Type: application/json;charset=utf-8{"title":"test","sub":[1,2,3]}

This solution can easily submit complex structured data and is especially suitable for RESTful interfaces. All major packet capture tools, such as Chrome's developer tools, Firebug, and Fiddler, will display JSON data in a tree structure, which is very friendly. However, some server languages do not support this method. for example, php cannot obtain content from the above request through the $ _ POST object. At this time, you need to handle it by yourself: when the Content-Type in the request header is application/json, get the original input stream from php: // input, and then json_decode the object. Some php frameworks have already started to do this.

Of course, AngularJS can also be configured to use x-www-form-urlencoded to submit data. If necessary, refer to this article.

Text/xml

My blog mentioned XML-RPC (XML Remote Procedure Call) before ). It is a remote call specification that uses HTTP as the transmission protocol and XML as the encoding method. The typical XML-RPC request is like this with the code below:

POST http://www.phprm.com HTTP/1.1Content-Type: text/xml
  
  
  
   examples.getStateName
   
   
    
   
    
     41
    
     
   
 

XML-RPC protocol is simple, functional enough, the implementation of various languages, it is also widely used, such as WordPress XML-RPC Api, seo/seo.html "target =" _ blank "> The ping service of the search engine. in JavaScript, there are also ready-made libraries that support data interaction in this way, can well support the existing XML-RPC service, however, I personally think the XML structure is too bloated, the general scenario with JSON will be more flexible and convenient.


Article address:

Reprint at will ^ please include the address of this article!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.