Home Web Front-end JS Tutorial Three Ajax implementation methods and AJAX parsing JSON

Three Ajax implementation methods and AJAX parsing JSON

Apr 25, 2018 am 11:57 AM
ajax javascript

This time I will bring you three Ajax implementation methods and AJAX parsing JSON. What are the precautions for Ajax three implementation methods and AJAX parsing JSON? Here are practical cases, let’s take a look.

Preparation:

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

Background 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例子后台处理程序 
 * @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); 
  } 
}
Copy after login

TestAjaxServlet receives two parameters: name and age, and returns a JSON String written in 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>
Copy after login

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['name'] + " age=" + objJson['age']; 
    } 
</script> 
<input id="submit" type="button" value="提交" onclick="prototypeAjax()" /><br />
Copy after login

In the Ajax implementation of prototype, use the evalJSON method to convert the string into a JSON object.

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>
Copy after login

I’m new to jQuery, and I’m in json The processing is done with the help of json2.js. 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 />
Copy after login

ps :Three ways to convert strings into JSON

During project development using Ajax, it is often necessary to return strings in JSON format to the front end, and the front end parses them into JS objects (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('(' + str + ')');
   return json;
}
Copy after login
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;
}
Copy after login
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);
}
Copy after login
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 = '{name:"jack"}';
var obj = JSON.parse(str); // --> parse error
Copy after login
name is not enclosed in quotation marks. When using JSON.parse, all browsers will throw Exception, parsing failed. The first two methods are fine.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jQuery creates a vertical translucent accordion effect

jquery implements the navigation menu mouse prompt function

The above is the detailed content of Three Ajax implementation methods and AJAX parsing JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

See all articles