Before how careful study of Ajax, just use it directly to use, found the problem to find a solution. Here's a little summary of what I'm looking for in the process of solving the problem.
A. Talking about the difference between get and post of Ajax
Get mode:
You can transfer simple data in Get mode, but the size is typically limited to 1KB, the data is appended to the URL (HTTP header transfer), that is, the browser appends individual form field elements and their data to the resource path in the request line in the format of the URL parameter. The most important point is that it is cached by the client's browser, so that other people can read the customer's data, such as account number and password, from the browser's history. Therefore, in some cases, the Get method poses a serious security problem.
Post Method:
When using post, the browser sends individual form field elements and their data to the Web server as the entity content of the HTTP message, rather than as a parameter to the URL address, and the amount of data that is passed by post is much larger than the amount of data that is transmitted using the GET method.
In short, get-mode transfer data is small, high processing efficiency, low security, will be cached, and post instead.
using Get method requires attention:
1 for Get requests (or any that involve passing parameters to the URL), the passed parameters are processed first by the encodeURIComponent method. Example: var url = "Update.php?username=" +encodeuricomponent ( username) + "&content=" +encodeuricomponent
(content) + "&id=1";
Use POST method to note:
1. Set header Context-type to Application/x-www-form-urlencode ensure that the server knows that there are parameter variables in the entity. The setrequestheader of the XMLHttpRequest object is usually used ( "Context-type", "application/x-www-form-urlencoded"). Cases:
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
2. The parameter is a name/value one by one corresponding to the key value pairs, each pair of values separated by the & number. like Var name=abc&sex=man&age=18, pay attention to Var name=update.php?
The abc&sex=man&age=18 and the Var name=?abc&sex=man&age=18 are all wrong;
3. Parameters sent in the Send (parameter) method, example: Xmlhttp.send (name); If it is a get way, direct xmlhttp.send (NULL);
4. Server-side request parameters differentiate get and post. If the Get method is $username = $_get["username"]; If it is the POST method, then $username = $_post["username"];
the Post and get methods have the following differences:
1.Post does not need to be displayed in the URL when transferring data, and the Get method is displayed in the URL.
2.Post transmits a large amount of data, can reach 2 m, and get method is limited by the URL length, can only pass about 1024 bytes.
3.Post as the name suggests, is to transfer data to the server segment, get is to obtain data from the server segment. And get can also send data, just designed to tell the server, you really need what kind of data. The post information is the content of the HTTP request, and get is transmitted over the HTTP header.
Get method receives with request.querystring["StrName"]
Post method receives with request.form["StrName"]
Attention:
Although both submissions can be unified using request ("StrName") to obtain submission data, this has an impact on program efficiency and is not recommended.
In general, try to avoid submitting forms using get methods, as it can lead to security issues
Ajax garbled Problem
The reason for the garbled:
1, Xtmlhttp returned the data default character encoding is Utf-8, if the client page is gb2312 or other encoded data will produce garbled
2, Post method submission data default character encoding is utf-8, if server-side is gb2312 or other encoded data will produce garbled
solution has:
1, if the client is gb2312 code, then specify the output stream code on the server
2, server-side and client are using UTF-8 encoding
Gb2312:header (' content-type:text/html;charset=gb2312 ');
Utf8:header (' Content-type:text/html;charset=utf-8 ');
Note: If you have already done so by the above method, or if you return garbled words, check if your method is get, for GET requests (or any of the URLs that involve passing parameters), The parameters that are passed are processed first by the encodeURIComponent method. If not treated with encodeuricomponent, it will produce garbled characters.
Below is an example that I found, because the good is posted here, write their own relatively simple, is not very normative or reference to the people wrote well, hehe!
Copy Code code 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 is 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
<?print_r ($_post);? > A large text box textarea has a lot of data, Ajax through the URL request service return results, the URL contains a variety of parameters, of course, also contains the previous large text box content. Before the development of the time to use Firefox in debugging, 4000-length string in the textarea inside the URL request is no problem. Submitted to the test when the problem came, the tester in IE found below the problem, textarea inside the character length of more than 2000 (probably data), will report JS error, Ajax did not return the value to the foreground. Look at the original code:
Copy Code code as follows:
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);
}
Online Google Discovery Solution: Modify the use of the XMLHTTP request for post, and separate the parameters and URLs to submit. The modified code is as follows:
Copy Code code as follows:
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 get and post two requests in Ajax October 04, 2008 Saturday 02:37 analysis of the similarities and differences of two submitting methods in Ajax we often use both a and post requests. So when do I ask for a request, and when do I post it? Before making an answer, we first need to understand the difference between get and post.
1, get is to add the parameter data queue to submit the form of the action attribute refers to the URL, the value and the form of each field one by one corresponding, in the URL can be seen. Post is the HTTP post mechanism that places the fields in the form and their contents in the HTML header to the URL address that the action attribute refers to. This process is not visible to the user.
2, for Get way, server end uses Request.QueryString to obtain variable value, for post way, server end uses Request.Form to obtain the submitted data. The parameters of both methods can be obtained by request.
3. The amount of data transferred by get is less than 2KB. Post transfers have a large amount of data, which is generally default to unrestricted. In theory, however, it varies depending on the server.
4, get security is very low, post security is high.
5, <form method= "get" action= "A.asp?b=b" > with <form method= "get" action= "a.asp" > is the same, that is to say, The list of arguments behind the action page when method is get is ignored, while <form method= "post" action= "A.asp?b=b" > and <form method= "Post action=" A.asp "> is not the same. The other GET request has the following characteristics: It adds the data to the URL, which is passed to the server in this way, usually using a question mark? Represents the end of a URL address and the beginning of a data parameter, with each data parameter in the form of a "name = value", which is differentiated between parameters and parameters using a connector &. Post requests have the following characteristics: The data is placed in the HTTP body, the organization of more than one, there are & connection, but also have the way of dividing, can hide parameters, transfer a large number of data, more convenient. Through the above instructions, now we have a general understanding of when to use get when the post way, yes! When we submit the form we usually use post, when we want to send a large data file, we need to use post. When the value passed is only in parameter mode (this value is not more than 2KB), you can use Get method. Now let's look at the difference between get and post when sending a request through a URL. The following example makes it easy to see the difference between the same data sent via Get and post, and the data sent is Username= John:
Copy Code code as follows:
Get/?username=%e5%bc%a0%e4%b8%89 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=%e5%bc%a0%e4%b8%89
The difference is that a form parameter and value are included in the URL request, one in the message entity of the HTTP request. By comparing the two paragraphs above, we will find that the Get mode places the form content in the previous request header, while Post puts the content in the requested body, while the Content-type header of the request is set to Application/x-www-form-ur in the post. Lencoded. The text sent is the same, so you can construct a form submission body: encodeURIComponent (arg1) =encodeuricomponent (value1) &encodeuricomponent (arg2) = encodeURIComponent (value2) ... Note: encodeURIComponent returns a new String object (Unicode format) that contains charstring content, and all spaces, punctuation, accented symbols, and other non-ASCII characters are replaced with%xx encodings, where xx equals the The hexadecimal number. For example, a space returns "%20". Characters with a value greater than 255 are stored in%UXXXX format. See the encodeURIComponent () method for JavaScript. After understanding the above content, we now use Ajax XMLHttpRequest objects to send some data to the server separately using get and post methods.
Get mode
Copy Code code 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 Code code 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 you are sending an XML file
Xmlhttp.send (postcontent);
The use of the Ajax Post method.
Just started to learn Ajax, see a lot of online code with get method to submit parameters, tomcat default ISO code is really a headache, deal with garbled I am using filter to do character encoding filter, get method filter is not listening, so I always like to use the Post method, the following on Ajax Get and Post methods do a comparison
Get:
Copy Code code as follows:
<mce:script type= "Text/javascript" ><!--
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 functions
function ProcessResponse () {
if (xmlhttprequest.readystate = = 4) {
if (Xmlhttprequest.status = = 200) {
var res = Xmlhttprequest.responsetext;
Window.alert (RES);
}else{
Window.alert ("Request page exception");
}
}
}
Authentication functions
function Usercheck () {
var userName = Document.loginForm.username.value;
var PSW = Document.loginForm.password.value;
if (UserName = = "") {
Window.alert ("User name 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>
<mce:script type= "Text/javascript" ><!--
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 functions
function ProcessResponse () {
if (xmlhttprequest.readystate = = 4) {
if (Xmlhttprequest.status = = 200) {
var res = Xmlhttprequest.responsetext;
Window.alert (RES);
}else{
Window.alert ("Request page exception");
}
}
}
Authentication functions
function Usercheck () {
var userName = Document.loginForm.username.value;
var PSW = Document.loginForm.password.value;
if (UserName = = "") {
Window.alert ("User name 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>
POST:
Copy Code code as follows:
<mce:script type= "Text/javascript" ><!--
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 ("POST", url,true);
Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-
Urlencoded ");
Xmlhttprequest.onreadystatechange = ProcessResponse;
Xmlhttprequest.send (param);
}
Processing return information functions
function ProcessResponse () {
if (xmlhttprequest.readystate = = 4) {
if (Xmlhttprequest.status = = 200) {
var res = Xmlhttprequest.responsetext;
Window.alert (RES);
}else{
Window.alert ("Request page exception");
}
}
}
Authentication functions
function Usercheck () {
var userName = Document.loginForm.username.value;
var PSW = Document.loginForm.password.value;
if (UserName = = "") {
Window.alert ("User name cannot be empty");
Document.loginForm.username.focus ();
return false;
}
else{
var url = "Servlet/userlogin_do?username=" +username+ "&psw=" +PSW;
var url = "Servlet/userlogin_do";
var param = "username=" +username+ "&psw=" +PSW;
Sendrequestpost (Url,param);
}
}
--></mce:script>
<mce:script type= "Text/javascript" ><!--
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 ("POST", url,true);
Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-
Form-urlencoded ");
Xmlhttprequest.onreadystatechange = ProcessResponse;
Xmlhttprequest.send (param);
}
Processing return information functions
function ProcessResponse () {
if (xmlhttprequest.readystate = = 4) {
if (Xmlhttprequest.status = = 200) {
var res = Xmlhttprequest.responsetext;
Window.alert (RES);
}else{
Window.alert ("Request page exception");
}
}
}
Authentication functions
function Usercheck () {
var userName = Document.loginForm.username.value;
var PSW = Document.loginForm.password.value;
if (UserName = = "") {
Window.alert ("User name cannot be empty");
Document.loginForm.username.focus ();
return false;
}
else{
var url = "Servlet/userlogin_do?"
Username= "+username+" &psw= "+PSW;
var url = "Servlet/userlogin_do";
var param = "username=" +username+ "&psw=" +PSW;
Sendrequestpost (Url,param);
}
}
--></mce:script>
As you can see, the Get method parses the parameters according to the address bar, and the post parses the parameters according to the Param string in Sendrequestpost (Url,param), which is important to add in the open () in the Post method. ; The method needs to add Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); This code, do not know why, beginner, You can pass the parameters by adding them, and study them later.