PHP using AJAX data submitted post and post common methods to summarize _php skills

Source: Internet
Author: User

This article illustrates the common methods used by PHP to submit post and post with Ajax data. Share to everyone for your reference. The specific methods are as follows:

In many cases we will not have any problems with Ajax, but sometimes encountered the Ajax data submission post incomplete problem, here for example to analyze.

Below is a standard AJAX request code, normally there will be no problem, but, in a particular case will be a problem, for example, when username=fdas&321, or the parameter value appears in the & symbol, after the N-pass test, found that the data are transmitted , but print out the data is half, the last careful observation of the head of the information found that the transmission of the head is wrong, the problem is located to JS, found that string splicing method will cause this problem username=fdas&321&password=password this is wrong. So we need to transform the transmitted data into {Username:username,passsword:password} This JSON format can avoid the problem!

The sample code is as follows:

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

Add: Four common methods of POST submission data

①application/x-www-form-urlencoded

This should be the most common way to POST-submit data. The native form form of the browser, if you do not set the Enctype property, the data will eventually be submitted in application/x-www-form-urlencoded mode. The request is similar to the following (the irrelevant request headers are omitted from this article):

Copy Code code 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, the Content-type is designated as application/x-www-form-urlencoded; second, the submitted data is encoded in a key1=val1&key2=val2 manner, and key and Val are both URL-transcoding. Most service-side languages have a good support for this approach. For example, in PHP, $_post[' title ' can get the value of title, $_post[' Sub ' can get a sub array.

Most of the time, we use Ajax to submit data, which is also used in this way. For example, the Ajax,content-type default values for JQuery and Qwrap are "application/x-www-form-urlencoded;charset=utf-8".

②multipart/form-data

This is another common way to POST data submissions. When we use a form to upload a file, we must have the enctyped of the form equal to this value. Look directly at a request example:

Copy Code code 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 slightly more complicated. First, a boundary is generated to segment different fields, and boundary is long and complex to avoid duplication with the body content. The Content-type then indicates that the data is encoded in Mutipart/form-data, and what the boundary of this request is. The number of fields in the message body is divided into a number of similar parts of the structure, each part is started with--boundary, followed by the content description information, then enter, and finally the specific content of the field (text or binary). If you are transferring files, also include file name and file type information. The message body finally ends with a--boundary--mark. For a detailed definition of mutipart/form-data, please go to rfc1867 view.

This way is generally used to upload files, the major service-side language for it also has good support.
The two types of POST data mentioned above are natively supported by browsers and are supported only by the native form form at this stage. But with more and more Web sites, especially WebApp, all using Ajax for data interaction, we can completely define new data submission methods and bring more convenience to development.

③application/json

Application/json this content-type as a response to the head everyone is certainly not unfamiliar. In fact, more and more people are using it as a request header to tell the server that the message body is a serialized JSON string. Because of the popularity of the JSON specification, the server-side language also has functions that handle JSON, except for the large browsers that are not in the lower version of IE, and there is no trouble using JSON.

The JSON format is also useful for supporting structured data that is much more complex than the key value pair. Remember when I was working on a project a few years ago, I needed to submit a very deep level of data, and I was submitting the data JSON serialization later. But at the time I was putting the JSON string as Val, still in the key-value pair, and submitting it in a x-www-form-urlencoded way.

The Ajax feature in Google's Angularjs, by default, is to submit a JSON string. For example, the following code:

Copy Code code as follows:
var data = {' title ': ' Test ', ' Sub ': [1,2,3]};
$http. Post (URL, data). Success (function (result) {
...
});

The final request to send is:
Copy Code code as follows:
POST http://www.jb51.net http/1.1
Content-type:application/json;charset=utf-8

{"title": "Test", "sub": [1,2,3]}

This scheme makes it easy to submit complex structured data, especially for RESTful interfaces. The big grab kits, such as Chrome's own developer tools, Firebug, and Fiddler, will display JSON data in a tree-like structure, very friendly. But there are also service-side languages that do not support this approach, such as PHP's inability to get content from the above request through the $_post object. At this time, need to deal with their own hands: in the request header Content-type as Application/json, from the Php://input to obtain the original input stream, and then json_decode into objects. Some PHP frameworks are already starting to do this.

Of course Angularjs can also be configured to submit data using the X-www-form-urlencoded method.

④text/xml

Previously mentioned XML-RPC (xml-based Remote Procedure call). It is a remote invocation specification that uses HTTP as a transport protocol and XML as a coding method. The typical XML-RPC request is this:

Copy Code code as follows:
POST http://www.jb51.net http/1.1
Content-type:text/xml

<!--? XML version= "1.0"?-->
<methodcall>
<methodname>examples.getStateName</methodname>
<params>
<param>
<value><i4>41</i4></value>

</params>
</methodcall>

XML-RPC protocol is simple, the function is sufficient, each kind of language realization has. It is also widely used, such as the WordPress-RPC api,seo/seo.html "target=" _blank > Search engine ping Services and so on. JavaScript, there are ready-made libraries that support data interaction in this way, and can support existing XML-RPC services well. However, I personally feel that the XML structure is still too bloated, the general scenario with JSON will be more flexible and convenient.

I hope this article will help you with your PHP program design.

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.