search
HomeWeb Front-endJS TutorialCompare three implementations of Ajax and JSON parsing

Compare three implementations of Ajax and JSON parsing

May 24, 2018 pm 02:09 PM
ajaxjavascriptjson

This article will introduce you to the three implementations of ajax and related information on json parsing. Friends who are interested in this article can refer to it

This article mainly compares three ways to implement Ajax, and provides a starting point for future learning. .

Preparation:

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例子后台处理程序 
 * @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.


Front page parameter input interface:

Html code

<p id="show">显示区域</p> 
<p id="parameters"> 
  name:<input id="name" name="name" type="text" /><br /> 
  age:<input id="age" name="age" type="text" /><br /> 
</p>

1. Prototype implementation

##Html code

<script type="text/javascript" src="prototype.js"></script> 
  <script type="text/javascript"> 
    function prototypeAjax() 
    {     
    var url = "servlet/testAjax";//请求URL 
    var params = Form.serialize("parameters");//提交的表单 
   var myAjax = new Ajax.Request( 
    url,{ 
      method:"post",// 请求方式  
      parameters:params, // 参数 
      onComplete:pressResponse, // 响应函数 
      asynchronous:true 
    }); 
    $("show").innerHTML = "正在处理中..."; 
    } 
    function pressResponse(request) 
    { 
    var obj = request.responseText; // 以文本方式接收 
    $("show").innerHTML = obj; 
    var objJson = request.responseText.evalJSON(); // 将接收的文本用解析成Json格式 
    $("show").innerHTML += "name=" + objJson[&#39;name&#39;] + " age=" + objJson[&#39;age&#39;]; 
    } 
</script> 
<input id="submit" type="button" value="提交" onclick="prototypeAjax()" /><br />

In prototype In Ajax implementation, the evalJSON method is used to convert strings into JSON objects.


##2. 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="提交" /><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: "GET",   
         contentType: "application/json",//注意请求页面的contentType 要于此处保持一致   
         success:function(data) {//这里的data是由请求页面返回的数据  
         var dataJson = JSON.parse(data); // 使用json2.js中的parse方法将data转换成json格式  
         $("#show").html("data=" + data + " name="+dataJson.name+" age=" + dataJson.age);   
         },   
         error: function(XMLHttpRequest, textStatus, errorThrown) {   
          $("#show").html("error"); 
         }   
      });   
    } 
    $("#submit").bind("click",jqueryAjax); // 绑定提交按钮 
 </script>

I just came into contact with jQuery and used json2.js to process json. I also ask my seniors for advice. .


##3. XMLHttpRequest implementation

Html code

<script type="text/javascript"> 
    var xmlhttp;  
    function XMLHttpRequestAjax()  
    { 
      // 获取数据 
     var name = document.getElementById("name").value;  
       var age = document.getElementById("age").value;  
     // 获取XMLHttpRequest对象 
     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; //回调函数 
       var time = new Date();// 在url后加上时间,使得每次请求不一样 
       var url = "servlet/testAjax?name="+name+"&age="+age+"&time="+time; 
       xmlhttp.open("GET",url,true); // 以get方式发送请求 
       xmlhttp.send(null);  // 参数已在url中,所以此处不需要参送 
    }    
    function callback(){   
      if(xmlhttp.readyState == 4){   
       if(xmlhttp.status == 200){ // 响应成功  
         var responseText = xmlhttp.responseText;  // 以文本方式接收响应信息 
         var userp = document.getElementById("show"); 
         var responseTextJson = JSON.parse(responseText); // 使用json2.js中的parse方法将data转换成json格式  
         userp.innerHTML=responseText + " name=" + responseTextJson.name + " age=" + responseTextJson.age; 
       } 
      }     
    } 
</script> 
<input id="submit" type="button" value="提交" onclick="XMLHttpRequestAjax()" /><br />

ps: Three ways to convert strings into JSON

During project development using Ajax, it is often necessary to convert JSON format into The string is returned to the front end, and the front end parses it into a JS object (JSON). ECMA-262(E3) did not write the JSON concept into the standard, but in ECMA-262(E5) the concept of JSON was officially introduced, including the global JSON object and the Date toJSON method.

1, eval method analysis, I am afraid this is the earliest analysis method.

function strToJson(str){
   var json = eval(&#39;(&#39; + str + &#39;)&#39;);
   return json;
}

Remember the parentheses on both sides of str.

2, the new Function form is quite weird.

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

In IE6/7, when the string contains a newline (\n), new Function cannot parse it, 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.

When using JSON.parse, you must strictly abide by the JSON specification. For example, attributes need to be enclosed in quotation marks, as follows

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

name is not enclosed in quotation marks Now, when using JSON.parse, exceptions are thrown in all browsers and parsing fails. The first two methods are fine.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.


Related articles:

How to solve the problem that error always pops up when ajax returns verification

Manual solution through Ajax WordPress WP-PostViews does not count the problem

##Analysis and solutions to the reasons why the data obtained by Ajax and put into echarts is not displayed


The above is the detailed content of Compare three implementations of Ajax and JSON parsing. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!