Summary of common methods for submitting post and post using ajax data in php

Source: Internet
Author: User
This article mainly introduces common methods for submitting post and post using ajax data in php. The example summarizes the advantages of passing data in json format and summarizes four common methods for submitting POST data, for more information, see the following example. Share it with you for your reference. The specific method is as follows:

In many cases, ajax is not a problem, but sometimes the problem of incomplete ajax data submission and post is encountered. here is an example for your analysis.

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. after N tests, all the data is transmitted, but the printed data is half-cut. Finally, we can observe the header information carefully and find that the transmitted header is incorrect, the problem is located in js. it is found that the string concatenation method will cause this problem. username = fdas & 321 & password = password is wrong. So we need to convert the transmitted data to the json format {username: username, passsword: password} to avoid the problem!

The sample code is as follows:

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 (){
}
})
})


Supplement: 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 application/x-www-form-urlencoded mode. The request is similar to the following (unrelated request headers are omitted in this article ):

The code is as follows:

POST http://www.jb51.net HTTP/1.1
Content-Type: application/x-www-form-urlencoded; charset = utf-8

Title = 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.jb51.net 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.

The Ajax function in AngularJS of Google submits JSON strings by default. For example, the following code:

The code is as follows:

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


The final request is:

The code is as follows:

POST http://www.jb51.net HTTP/1.1
Content-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.

④ Text/xml

XML-RPC (XML Remote Procedure Call) was mentioned earlier ). It is a remote call specification that uses HTTP as the transmission protocol and XML as the encoding method. A typical XML-RPC request is like this:

The code is as follows:

POST http://www.jb51.net HTTP/1.1
Content-Type: text/xml



Examples. getStateName


41



XML-RPC protocol is simple, the function is enough, the realization of various languages have. It is also widely used, such as WordPress XML-RPC Api, seo/seo.html "target =" _ blank "> Search engine ping service and so on. In JavaScript, there are also ready-made libraries to support data interaction in this way, can well support the existing XML-RPC services. However, I personally think the XML structure is too bloated, and JSON is more flexible and convenient in general scenarios.

I hope this article will help you with PHP programming.

Related 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.