This paper is mainly to compare three kinds of ways to realize Ajax, for the future learning to open a head.
Get ready:
1, Prototype.js
2, Jquery1.3.2.min.js
3, Json2.js
Background handler (Servlet), Access path Servlet/testajax:
Java code
Package ajax.servlet;
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;
/** * Ajax Example Background handler * @author Bing * @version 2011-07-07 */public class Testajaxservlet extends HttpServlet { public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio
n {response.setcontenttype ("text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
String name = Request.getparameter ("name");
String age = request.getparameter (' age ');
System.out.println ("{\" name\ ": \" "+ name +" \ ", \" age\ ": \" "+ Age +" \ "}");
Out.print ("{\" name\ ": \" "+ name +" \ ", \" age\ ":" + Age + "}");
Out.flush ();
Out.close (); public void DoPost (HttpServletRequest request, httpservletresponse response) throws ServletexceptioN, IOException {doget (request,response); }
}
Testajaxservlet receives two parameters: Name and age, and returns a string written in JSON format.
Front page parameter Input interface:
HTML code
<div id= "Show" > Display area </div>
<div id= "Parameters" >
name:<input id= "name" name= "name" type = "text"/><br/>
age:<input id= "age" name= "age" type= "text"/><br/>
First, prototype implementation
HTML code
<script type= "Text/javascript" src= "prototype.js" ></script>
<script type= "Text/javascript" >
function Prototypeajax ()
{
var url = "Servlet/testajax";//Request URL
var params = form.serialize ("parameters");/Submit Form
var myajax = new Ajax.request (
url,{
method: "POST",//Request mode
Parameters:params,//Parameter
Oncomplete:pressresponse,// Response function
asynchronous:true
});
$ ("show"). InnerHTML = "in process ...";
}
function Pressresponse (Request)
{
var obj = request.responsetext//receives
$ ("show") in text. InnerHTML = obj;
' Name ' + ' age= ' + objjson[' age ';
}
</script>
In the AJAX implementation of prototype, a Evaljson method is used to convert a string into a JSON object.
Second, jquery implementation
HTML code
<script type= "Text/javascript" src= "jquery-1.3.2.min.js" ></script> <script type= "Text/javascript" Src= "Json2.js" ></script> <input id= "Submit" type= "button" value= "Submit"/><br,/> <script, type= "
Text/javascript "> Function Jqueryajax () {var user={" name ":" "," Age ":"};
User.name= $ ("#name"). Val ();
user.age=$ ("#age"). Val ();
var time = new Date ();
$.ajax ({url: "servlet/testajax?time=" +time, Data: "Name=" +user.name+ "&age=" +user.age, DataType: "JSON",//The requested page returns the data type: "Get", ContentType: "Application/json",//Note Request page Contentt Ype to stay consistent here. Success:function (data) {//Here is the information returned by the request page var Datajson = json.parse (data);//Use JSO
The parse method in N2.js converts data to JSON format $ ("#show"). HTML ("Data=" + Data + "name=" +datajson.name+ "age=" + datajson.age); }, Error:function (XMLHttpRequest, TextstatUS, Errorthrown) {$ ("#show"). HTML ("error");
}
}); $ ("#submit"). Bind ("click", Jqueryajax); Bind Submit Button </script>
Just contact jquery, with the help of JSON json2.js. Also ask seniors to advise.
Third, XMLHttpRequest implementation
HTML code
<script type= "Text/javascript" > var xmlhttp;
function Xmlhttprequestajax () {//Get data var name = document.getElementById (' name '). Value;
var age = document.getElementById (' age '). Value; Gets the XMLHttpRequest object if (window).
XMLHttpRequest) {xmlhttp = new XMLHttpRequest (); }else if (window. ActiveXObject) {var activxname = ["MSXML2.
XMLHTTP "," Microsoft.XMLHTTP "];
for (var i = 0; i < activexname.length i++) {try{xmlhttp = new ActiveXObject (activexname[i));
Break }catch (e) {}}} Xmlhttp.onreadystatechange = callback; The callback function var time = new Date ();//After the URL plus the times so that each request is not the same var url = "Servlet/testajax?name=" +name+ "&age=" +ag
E+ "&time=" +time; Xmlhttp.open ("Get", url,true); Send request Xmlhttp.send (NULL) in Get mode; parameter is already in the URL, so there is no need to join} function callback () {if (xmlhttp.readystate = 4) {if (Xmlhttp.status = = 200) {//Response success var responsetext = Xmlhttp.responsetext;
Receive response information in text var userdiv = document.getElementById ("show"); var Responsetextjson = Json.parse (responsetext); Use the Parse method in Json2.js to convert data to JSON format Userdiv.innerhtml=responsetext + "Name=" + responsetextjson.name + "age="
"+ responsetextjson.age; <input id= "Submit" type= "button" value= "submitted" onclick= "Xmlhttprequestajax ()"/> ; <br/>
PS: Three ways to convert strings into JSON
In the process of developing an AJAX project, it is often necessary to return the JSON-formatted string to the front end and parse the front end into a JS object (JSON).
The JSON concept was not written to the standard in ECMA-262 (E3), but the concept of JSON was formally introduced in ECMA-262 (E5), including global JSON objects and date Tojson methods.
1,eval Way of parsing, I am afraid this is the earliest analytic way.
function Strtojson (str) {
var json = eval (' + str + ') ');
return JSON;
Remember the parenthesis on both sides of the Str.
2,new function form, more bizarre Oh.
function Strtojson (str) {
var json = (new Function ("return" + str)) ();
return JSON;
When the string contains a newline (\ n) in the IE6/7, the new function cannot parse, but Eval can.
3, use the global JSON object.
function Strtojson (str) {return
json.parse (str);
Currently IE8 (S)/FIREFOX3.5+/CHROME4/SAFARI4/OPERA10 has implemented this method.
The use of json.parse requires strict adherence to the JSON specification, such as a property that is enclosed in quotes, as follows
var str = ' {name: ' Jack '} ';
Name is not enclosed in quotation marks, and parsing fails with the exception being thrown in all browsers using Json.parse. The first two ways are fine.