Home >Web Front-end >JS Tutorial >分享ajax三种实现方法

分享ajax三种实现方法

WBOY
WBOYOriginal
2016-06-01 09:54:191096browse

本文主要是比较三种实现Ajax的方式,为以后的学习开个头。

准备:

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

后台处理程序(Servlet),访问路径servlet/testAjax:

Java代码

<code class="language-java">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); 
  } 
}</code>

TestAjaxServlet接收两个参数:name和age,并返回一个以JSON格式编写的字符串。

前台页面参数输入界面:

Html代码 

<code class="language-html"><div id="show">显示区域</div> 
<div id="parameters"> 
  name:<input id="name" name="name" type="text"><br> 
  age:<input id="age" name="age" type="text"><br> 
</div></code>

 

一、prototype实现

<code class="language-html"><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>
</code>

在prototype的Ajax实现中,用evalJSON方法将字符串转换成JSON对象。

 

二、jquery实现

<code class="language-html"><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>
</code>

刚接触jQuery,在json的处理上借助了json2.js。还请前辈们指教。

 

三、XMLHttpRequest实现

<code class="language-html"><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 userdiv = document.getElementById("show"); 
         var responseTextJson = JSON.parse(responseText); // 使用json2.js中的parse方法将data转换成json格式  
         userdiv.innerHTML=responseText + " name=" + responseTextJson.name + " age=" + responseTextJson.age; 
       } 
      }     
    } 
</script> 
<input id="submit" type="button" value="提交" onclick="XMLHttpRequestAjax()"><br>
</code>

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