Two ways of submitting Ajax (Get/post) and two versions of _ajax related

Source: Internet
Author: User
Recently more idle, the previous use of the technology string to do a codex, convenient after their lazy, birds you happy.

First of all, the JavaScript version of Ajax to make the comments: Ajax asynchronous refresh is mainly the required conditions into a string into the background, after processing, directly invoke the callback function to return the data to the page, and to display, because still in this page, so do not refresh the page, understand it, This article also uses the encodeURI to encrypt the string, and in the class to do the decoding, which needs some attention in the source code to do the annotation. Get/post two ways to submit, but get submitted easily garbled, be sure to pay more attention to

JSP page:
Copy Code code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >
<script type= "Text/javascript" >
var xmlHttp;
function Createxmlhttprequest () {
if (window. XMLHttpRequest) {
xmlhttp= new XMLHttpRequest ();//ie7+,firefox,opera,safari,chrome
}else{
Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
}
}
function test () {//get
Get parameters
var Unames=encodeuri (document.getElementById ("username"). value);//Once coded Java with new String (Name.getbytes ("iso8859-1 ")," UTF-8 ") decoding
var Unames=encodeuri (encodeURI (document.getElementById ("username"). value);//two times code can be used Java.net.URLDecoder.decode ( Name, "Utf-8");
var Pws=encodeuri (document.getElementById ("password"). value);
Createxmlhttprequest ();
Xmlhttp.onreadystatechange=readystate;
function () {
Alert (xmlhttp.readystate+ "= =" +xmlhttp.status)//Judge request status
//}
Xmlhttp.open ("Get", "Ajaxservlet1?msg=gets&name=" +unames+ "&pwd=" +pws+ "&timestamp=" +new Date (). GetTime (), true); Get way to submit Chinese will appear garbled, encodeURI ()/encodeuricomponent () into the Chinese into 16 encoding, the string as a URI encoding
Xmlhttp.send (NULL);
}
function testp () {//post
Get parameters
var Unames=document.getelementbyid ("username"). Value;
var Pws=document.getelementbyid ("password"). Value;
Createxmlhttprequest ();
Xmlhttp.onreadystatechange=readystate;
Xmlhttp.open ("Post", "AjaxServlet1", true);
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
var str= "msg=posts&name=" +unames+ "&pwd=" +pws+ "&timestamp=" +new Date (). GetTime ();
Xmlhttp.send (str);//send can be used to pass parameters
}

function ReadyState () {
if (xmlhttp.readystate==4) {
if (xmlhttp.status==200) {
var msg= xmlhttp.responsetext;
Alert (msg);
document.getElementById ("Result"). Innerhtml=msg;
}
}
}
</script>
<title>js Asynchronous Refresh </title>

<body>
<center>
<div id= "Response" >
</div>
User: <input type= "text" name= "uname" id= "username" ><br>
Password: <input type= "text" name= "PW" id= "password" ><br>
<input type= "button" name= "button" value= "Get OK" onclick= "test ();" />
<input type= "button" name= "button" value= "Post determines" onclick= "TESTP (); >
<div id= "Result" >
</div>
</center>
</body>


Here is servlet/action Java code:
Copy Code code as follows:

Package com.cstp.javascript;

Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

@SuppressWarnings ("Serial")
public class AjaxServlet1 extends HttpServlet {

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
This.dopost (request, response);
}

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Set code to prevent garbled
Response.setcharacterencoding ("Utf-8");
Request.setcharacterencoding ("Utf-8");
Receive parameters
String msg=request.getparameter ("msg");
if (Msg.equals ("gets")) {
String Name=new string (Request.getparameter ("name"). GetBytes ("Iso8859-1"), "UTF-8"); Encoding in one time, decoding operations in Java
String Name=java.net.urldecoder.decode (Request.getparameter ("name"), "Utf-8"); Decode decoding page must be encoded two times, decoding operation in Java
String pwd=request.getparameter ("pwd");
System.out.println (name+ "," +pwd);
PrintWriter out = Response.getwriter ();
OUT.PRINTLN ("Ajax response Get, result returns" +name+ "," +pwd);
}else if (msg.equals ("posts")) {
String Name=new string (Request.getparameter ("name"). GetBytes ("Utf-8"), "UTF-8"); Encoding in one time, decoding operations in Java
String pwd=request.getparameter ("pwd");
System.out.println (name+ "," +pwd);
PrintWriter out = Response.getwriter ();
OUT.PRINTLN ("Ajax response post, the result returns" +name+ "," +pwd);
}

}
}

The above is a JavaScript version of Ajax, the following will like the jquery version of also share to JQ friends:

On the page:
Copy Code code as follows:

<script type= "Text/javascript" >
Way ①
function Circum (Lon,lat) {
$.ajax ({
URL: "Jqajaxservlet?method=jsons",
ContentType: "application/x-www-form-urlencoded; Charset=utf-8 ",
Type: ' Post ',
DataType: "JSON",
Async:false,
Data: {//Pass the reference to the background
' Lon ': Lon,
' Lat ': Lat
},
Success:function (data) {//Backend return result
In this case data is returned to the background, you can deal with it
}
});
}

</script>

Backstage: Servlet/action.

The method of data processing in the class above, is no longer a burden

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.