Home > Web Front-end > JS Tutorial > body text

Description, usage and difference between get and post in ajax_javascript skills

WBOY
Release: 2016-05-16 17:45:41
Original
1006 people have browsed it

I haven't studied ajax very carefully before. I just used it when I used it. I found problems and then found solutions. The following is a small summary of my process of finding solutions to problems.

1. Talking about the difference between Ajax Get and Post
Get method:
Using the get method to transmit simple data, but the size is generally limited to 1KB, the data is appended to the url Send in (HTTP header transmission), that is to say, the browser appends each form field element and its data to the end of the resource path in the request line in the format of URL parameters. The most important thing is that it will be cached by the client's browser, so others can read the customer's data, such as account number and password, etc. from the browser's history. Therefore, in some cases, the get method can cause serious security issues.
Post method:
When using the POST method, the browser sends each form field element and its data to the web server as the entity content of the HTTP message, rather than as parameters of the URL address. Transmission, the amount of data transmitted using POST method is much larger than that using GET method.
In short, the GET method transmits a small amount of data, high processing efficiency, low security, and will be cached, while the opposite is true for POST.

When using the get method, please note: :
1 For get requests (or any involving url passed parameters), the passed parameters must first be processed by the encodeURIComponent method. Example: var url = "update.php?username=" encodeURIComponent(username) "&content=" encodeURIComponent
(content) "&id=1" ;
Be careful when using the Post method:
1. Set the Context-Type of the header to application/x-www-form-urlencode to ensure that the server knows that there are parameter variables in the entity. Usually SetRequestHeader("Context-Type", "application/x-www-form-urlencoded" of the XmlHttpRequest object is used ;"). Example:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2. The parameters are key-value pairs with one-to-one name/value correspondence. Each pair of values ​​uses Separated by ampersand. For example, var name=abc&sex=man&age=18, please note that var name=update.php?
abc&sex=man&age=18 and var name=?abc&sex=man&age=18 are both wrong;
3. Parameters are sent in the Send (parameter) method, for example: xmlHttp.send(name); If it is the get method, directly xmlHttp.send(null);
4. Server-side request parameters distinguish Get and Post. If it is the get method, then $username = $_GET["username"]; If it is the post method, then $username = $_POST["username"];

The differences between the Post and Get methods are as follows:
1. When Post transmits data, it does not need to be displayed in the URL, but the Get method must be displayed in the URL.
2.Post transmits a large amount of data, which can reach 2M, while the Get method can only transfer about 1024 bytes due to the URL length limit.
3.Post, as the name suggests, is to transmit data to the server segment , Get is to obtain data from the server segment. The reason why Get can also transmit data is only designed to tell the server what kind of data you need. Post information is used as the content of the http request, and Get is in the Http header. transmitted.
The get method uses Request.QueryString["strName"] to receive
The post method uses Request.Form["strName"] to receive
Note:
Although the two submission methods can be unified, Request("strName ") to obtain submitted data, but this has an impact on program efficiency and is not recommended.
Generally speaking, try to avoid using the Get method to submit a form, because it may cause security problems

AJAX garbled code problem
Causes of garbled code:
1. The default character encoding of the data returned by xtmlhttp is utf-8. If the client page is gb2312 or other encoded data, garbled characters will be generated
2. The default character encoding of the data submitted by the post method is utf-8. If the server is gb2312 Or other encoded data will produce garbled characters

The solutions are:
1. If the client is gb2312 encoding, specify the output stream encoding on the server
2. Server side Both the client and the client use utf-8 encoding
gb2312:header('Content-Type:text/html;charset=GB2312');
utf8:header('Content-Type:text/html;charset=utf -8');
Note: If you have done the above method and still return garbled characters, check whether your method is get. For get requests (or anything involving url passing parameters), the passed The parameters must be processed by the encodeURIComponent method first. If they are not processed by encodeURIComponent, garbled characters will also be produced.
Below is an example I found. Because it is well written, I posted it here. The one I wrote is relatively simple, and it is not It’s very standard, so it’s better to refer to what others have written, haha!

Copy code The code is as follows:

var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
function get(obj) {
var poststr = "mytextarea1=" encodeURI( document.getElementById("mytextarea1").value )
"&mytextarea2=" encodeURI( document.getElementById("mytextarea2").value );
makePOSTRequest('post.php', poststr);
}

post.php
一个超大文本框textarea里面有大量数据,ajax通过URL请求service返回结果,URL里面包含了各种参数,当然也包含之前的超大文本框的内容。 之前开发的时候一直用Firefox在调试,4000长度的字符串在textarea里面通过URL请求都是没有问题。 提交给测试的时候问题来了,测试人员在IE下面发现问题,textarea里面字符长度超过2000(大概数据)时,会报JS错误,ajax没有返回值给前台。 看原先代码:
复制代码 代码如下:

function getJsonData(url)
{
var ajax = Common.createXMLHttpRequest();
ajax.open("GET",url,false);
ajax.send(null);
try
{
eval("var s = " ajax.responseText);
return s;
}
catch(e)
{
return null;
}
}
function getData(){
var url="BlacklistService.do?datas=" datasvalue;
var result = getJsonData(url);
}

网上google发现解决办法: 修改使用的XMLHttp的请求为POST,并且把参数和URL分离出来提交。 修改后代码如下:
复制代码 代码如下:

function getJsonData(url,para)
{
var ajax = Common.createXMLHttpRequest();
ajax.open("POST",url,false);
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(para);
try
{
eval("var s = " ajax.responseText);
return s;
}
catch(e)
{
return null;
}
}
function getData(){
var url="BlacklistService.do";
var para="datas=" datasvalue;
var result = getJsonData(url,para);
}

================================
The similarities and differences between the get and post request methods in Ajax Saturday, October 4, 2008 02:37 pm Analyze the similarities and differences between the two submission methods. In Ajax, we often use get and post requests. So when to use get requests and when to use post requests? Before answering, we first To understand the difference between get and post.
1. Get adds the parameter data queue to the URL pointed to by the ACTION attribute of the submitted form. The value corresponds to each field in the form one-to-one and can be seen in the URL. Post uses the HTTP post mechanism to place each field in the form and its content in the HTML HEADER and transmit it to the URL address pointed to by the ACTION attribute. Users cannot see this process.
2. For the get method, the server side uses Request.QueryString to obtain the value of the variable. For the post method, the server side uses Request.Form to obtain the submitted data. Parameters in both ways can be obtained using Request.
3. The amount of data transmitted by get is small and cannot be larger than 2KB. The amount of data transmitted by post is relatively large and is generally unrestricted by default. But in theory, it varies from server to server.
4. The security of get is very low, but the security of post is high.
5.
is the same as , that is That is, when the method is get, the parameter list at the end of the action page will be ignored; and and is different. In addition, the Get request has the following characteristics: it will add data to the URL and pass it to the server in this way, usually using a question mark? Represents the end of the URL address and the beginning of the data parameters. Each data parameter of the following parameters appears in the form of "name = value", and the parameters are distinguished by a connector &. The Post request has the following characteristics: the data is placed in the HTTP body, and it is organized in more than one way, including the & connection method and the separator method. It can hide parameters and transfer large amounts of data, which is more convenient. Through the above explanation, now we have a rough understanding of when to use get and when to use post method, right! When we submit a form, we usually use post method. When we want to transmit a larger data file, we need to Use post. When the value passed only needs to be in parameter mode (the value is not larger than 2KB), use the get method. Now let's look at the difference between the get method and the post method when sending a request through the URL. Using the following example, you can easily see the difference between sending the same data through GET and POST. The data sent is username=Zhang San:
Copy code The code is as follows:

GET /?username=张三HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/ pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User- Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
Host: localhost
Connection: Keep-Alive
POST Method:
POST / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
Accept -Language: zh-cn
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
Host: localhost
Content-Length: 28
Connection: Keep-Alive
username=张三

The difference is one The form parameters and values ​​are attached to the URL request, and one is in the message entity of the HTTP request. Comparing the two paragraphs above, we will find that the GET method puts the form content in the previous request header, while the POST method puts these contents in the body of the request. At the same time, the Content-Type header of the request is set in POST. application/x-www-form-urlencoded. The text sent is the same. You can construct a form submission text like this: encodeURIComponent(arg1)=encodeURIComponent(value1)&encodeURIComponent(arg2)=encodeURIComponent(value2)&... ..Note: encodeURIComponent returns a new String object (Unicode format) containing the content of charstring. All spaces, punctuation, accents and other non-ASCII characters are replaced by %xx encoding, where xx is equal to the hexadecimal representation of the character. system number. For example, spaces are returned as " ". Character values ​​greater than 255 are stored in %uxxxx format. See JavaScript's encodeURIComponent() method. After understanding the above, we now use ajax's XMLHttpRequest object to send some data to the server using GET and POST methods respectively.

GET method
Copy code The code is as follows:

var postContent ="name=" encodeURIComponent("xiaocheng") "&email=" encodeURIComponent("xiaochengf_21@yahoo.com.cn");
xmlhttp.open("GET", "somepage" "?" postContent, true);
xmlhttp.send(null);

POST method
Copy the code The code is as follows:

var postContent ="name=" encodeURIComponent("xiaocheng") "&email=" encodeURIComponent("xiaochengf_21@yahoo.com.cn ");
xmlhttp.open("POST", "somepage", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-Type", "text/xml"); //If an xml file is sent
xmlhttp.send(postContent);


Using Ajax's post method.
I just started learning Ajax and saw that many online codes use the Get method to submit parameters. Tomcat's default ISO encoding is really a headache. I always use it to deal with garbled characters. The filter does character encoding filtering, and the Get method filter cannot monitor it, so I always like to use the Post method. Here is a comparison of the Ajax Get and Post methods
GET:
Copy code The code is as follows:

< !--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{

// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{

try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX! ");
return false;
}
}
}

}
//Send request function
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("GET",url "?" param,true);
xmlHttpRequest.onreadystatechange = processResponse;
}
//Processing return information function
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("Request page exception");
}
}
}
//Authentication function
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("Username cannot be Empty");
document.loginForm.username.focus();
return false;
}
else{
var url = "Servlet/userLogin_do";
var param = "userName=" userName "&psw=" psw;
sendRequestPost(url,param);
}
}
// -->

< mce:script type="text/javascript">

POST:
Copy code The code is as follows:




It can be found that the GET method parses parameters according to the address bar, and post parses parameters according to the param string in sendRequestPost(url,param);. The important thing is that the POST method needs to be added in open (); You need to add xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); after the method. I don’t know why. I am a beginner. If you add it, you can pass parameters. I will study it in the future. .
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template