Compare three Ajax implementations and JSON parsing,

Source: Internet
Author: User
Tags add time parse error

Compare three Ajax implementations and JSON parsing,

This article mainly compares three methods to implement Ajax, opening the door for future learning.

Preparation:

1. prototype. js
2. jquery1.3.2.min. js
3. json2.js

Backend Processing Program (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, IOException {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.

Parameter input interface on the foreground page:

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/> </div>

1. 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"); // The submitted Form var myAjax = new Ajax. request (url, {method: "post", // Request method parameters: params, // parameter onComplete: pressResponse, // response function asynchronous: true }); $ ("show "). innerHTML = "processing... ";} function pressResponse (request) {var obj = request. responseText; // receives $ ("show") in text format "). innerHTML = obj; var objJson = request. responseText. evalJSON (); // parse the received text into Json format $ ("show "). innerHTML + = "name =" + objJson ['name'] + "age =" + objJson ['age'];} </script> <input id = "submit" type = "button" value = "submit" onclick = "prototypeAjax ()"/> <br/>

In the Ajax Implementation of prototype, the evalJSON method is used to convert the string into a JSON object.

Ii. 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", // type returned by the request page: "GET", contentType: "application/json ", // note that the contentType of the request page must be consistent here success: function (data) {// The data here is the data returned by the request page var dataJson = JSON. parse (data); // use the parse method in json2.js to convert data to the 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 the submit button </script>

I just got started with jQuery and used json2.js for json processing. Please advise me ..

Iii. XMLHttpRequest implementation

Html code

<Script type = "text/javascript"> var xmlhttp; function XMLHttpRequestAjax () {// obtain data var name = document. getElementById ("name "). value; var age = document. getElementById ("age "). value; // obtain 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 ++) {tr Y {xmlhttp = new ActiveXObject (activexName [I]); break;} catch (e) {}} xmlhttp. onreadystatechange = callback; // callback function var time = new Date (); // Add time after the url to make each request different from var url = "servlet/testAjax? Name = "+ name +" & age = "+ age +" & time = "+ time; xmlhttp. open ("GET", url, true); // send the request xmlhttp in get mode. send (null); // The parameter is already in the url, so no parameter is required here} function callback () {if (xmlhttp. readyState = 4) {if (xmlhttp. status = 200) {// response success var responseText = xmlhttp. responseText; // receive response information in text mode var userdiv = document. getElementById ("show"); var responseTextJson = JSON. parse (responseText); // use the parse method in json2.js to convert data to the json format userdiv. innerHTML = responseText + "name =" + responseTextJson. name + "age =" + responseTextJson. age ;}}</script> <input id = "submit" type = "button" value = "submit" onclick = "XMLHttpRequestAjax ()"/> <br/>

Ps: three methods for String Conversion to JSON

During Ajax project development, strings in JSON format are often returned to the front end, and the front end is parsed into JS objects (JSON ).
The JSON concept was not written to the standard in ECMA-262 (E3), but in ECMA-262 (E5) The JSON concept was formally introduced, including the Global JSON object and the toJSON method of Date.

1. eval parsing. I'm afraid this is the earliest parsing method.

function strToJson(str){   var json = eval('(' + str + ')');   return json;} 

Remember the parentheses on both sides of str.

2. The new Function format is weird.

function strToJson(str){  var json = (new Function("return " + str))();  return json;} 

In IE6/7, when a string contains a line break (\ n), the new Function cannot be parsed, but the eval can.

3. Use a global JSON object.

function strToJson(str){  return JSON.parse(str);} 

Currently, IE8 (S)/Firefox3.5 +/Chrome4/Safari4/Opera10 has implemented this method.

JSON. parse must comply with JSON specifications strictly. If attributes are enclosed by quotation marks

var str = '{name:"jack"}';var obj = JSON.parse(str); // --> parse error 

Name is not enclosed in quotation marks. If JSON. parse is used, an exception is thrown in all browsers and parsing fails. The first two methods are fine.

Articles you may be interested in:
  • Jquery ajax cannot parse json objects. The cause and solution of Invalid JSON error are reported.
  • Analysis of ajax request json data and js parsing (Example Analysis)
  • Php + mysql combined with Ajax to implement a complete example of the like feature
  • PHP + jQuery + Ajax for multi-Image Upload
  • Php + ajax + jquery click to load more content
  • Comparison and Analysis of Two Methods for parsing Json in Ajax
  • JQuery + AJAX implement no refreshing drop-down load more
  • JQuery + Ajax + PHP + Mysql: display data by PAGE
  • Combined with php, jquery achieves LongPoll)
  • JQuery + AJAX: Mask Layer logon verification interface (with source code)

Related Article

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.