Home Web Front-end JS Tutorial Description, usage and difference between get and post in ajax_javascript skills

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

May 16, 2016 pm 05:45 PM
ajax get post

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to automate tasks using PowerShell How to automate tasks using PowerShell Feb 20, 2024 pm 01:51 PM

If you are an IT administrator or technology expert, you must be aware of the importance of automation. Especially for Windows users, Microsoft PowerShell is one of the best automation tools. Microsoft offers a variety of tools for your automation needs, without the need to install third-party applications. This guide will detail how to leverage PowerShell to automate tasks. What is a PowerShell script? If you have experience using PowerShell, you may have used commands to configure your operating system. A script is a collection of these commands in a .ps1 file. .ps1 files contain scripts executed by PowerShell, such as basic Get-Help

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to implement PHP to jump to the page and carry POST data How to implement PHP to jump to the page and carry POST data Mar 22, 2024 am 10:42 AM

PHP is a programming language widely used in website development, and page jumps and carrying POST data are common requirements in website development. This article will introduce how to implement PHP page jump and carry POST data, including specific code examples. In PHP, page jumps are generally implemented through the header function. If you need to carry POST data during the jump process, you can do it through the following steps: First, create a page containing a form, where the user fills in the information and clicks the submit button. Acti in the form

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

See all articles