经过XMLHttpRequest和jQuery实现ajax的几种方式

AJAX你们已经都知道了,是为了实现异步通信,提升用户体验度,而将不少旧知识(XML,DOM,JavaScript,HTML,Jquery,Css……)从新融合的一个新的知识框架。而,XMLHttpRequest对象则是其中的重重之中,本篇文章主要给你们介绍经过XMLHttpRequest和jQuery实现ajax的几种方式javascript

HTML代码:html

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
  <script type="text/javascript" src="Scripts/jwy.js"></script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" name="textbox" id="text1" />
    <input type="button" name="button" id="Button1" value="显示时间" onclick="btnclick()" />
  </div>
  </form>
</body>
</html>

  

建立一个“通常处理程序”来处理前台请求,返回系统当前时间:java

Handler.ashxjquery

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Text;
public class Handler : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "text/plain";
    context.Response.Write(ShowTime());
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
  public static string ShowTime()
  {
    return DateTime.Now.ToString();
  }
}

  

js代码:web

function btnclick() {
  var httprequest = null;
  // 初始化XMLHttpRequest对象
  if (window.XMLHttpRequest) {
    // Firefox等现代浏览器中的XMLHttpRequest对象建立
    httprequest = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    // IE中的XMLHttpRequest对象建立
    httprequest = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (!httprequest) {
    alert("建立httprequest对象出现异常!");
  }
  httprequest.open("POST", "Handler.ashx", true);
  //httprequest向handler发送post请求,最后参数是设定是否为异步请求,true为异步,false为同步
  httprequest.onreadystatechange = function () {
    //指定onreadystatechange事件句柄对应的函数
    if (httprequest.readyState == 4) {
      //4表明服务器返回完成
      if (httprequest.status == 200) {
        //200表明成功了
        document.getElementById("text1").value = httprequest.responseText;
        //responsetext表示服务器返回的文本,还有一种方式是responseXML是为了获取服务器返回的xml
      }
      else {
        alert("AJAX服务器返回错误!");
      }
    }
  }
  httprequest.send();
  //在这里才真正的向服务器端发送请求
}

  

咱们用jquery来前台js代码会变得十分简洁:ajax

基于jquery编写的js代码json

注意:HTML代码要把button的onclick事件去掉,由于咱们直接在js用了事件绑定。浏览器

$(document).ready(function () {
  //button1绑定事件
  $("#Button1").bind("click", function () {
    $.ajax({
      url: "Handler.ashx",
      type: "POST",
      success: function (data) {
        //$("#text1").val(data);
        document.getElementById("text1").value = data;
      }
    });
  });
});

  

不得不说jquery“简约而不简单”……服务器

jquery中的$.ajax集合了get、post方法,默认的是get。框架

若是直接用POST的话,代码更简单

$(document).ready(function () {
  //button1绑定事件
  $("#Button1").bind("click", function () {
    $.post("Handler.ashx", function (data) {
  document.getElementById("text1").value = data;
    }); 
 });
});

  

示例二:

1、XMLHttpRequest实现获取数据

不使用jQuery实现页面不刷新获取内容的方式,咱们这里采用XMLHttpRequest原生代码实现;

js代码以下:

//1.获取a节点,并为其添加Oncilck响应函数
document.getElementsByTagName("a")[0].onclick = function(){
   //三、建立一个XMLHttpRequest();
  var request = new XMLHttpRequest();
  //四、准备发送请求的数据url
  var url = this.href;
  var method = "GET";
  //五、调用XMLHttpRequest对象的open方法
  request.open(method,url);
  //六、调用XMLHttpRequest对象的send方法
  request.send(null);
  //七、为XMLHttpRequest对象添加onreadystatechange 响应函数
  request.onreadystatechange = function(){
    //八、判断响应是否完成:XMLHttpRequest 对象的readystate的属性值为4的时候
    if(request.readyState == 4){
       //九、在判断响应是否可用:XMLHttpRequest 对象status 属性值为200
      if(request.status == 200){
           //十、响应结果
           alert(request.responseText);
      }  
    } 
  }   
      //二、取消a节点的额默认行为
      return false;   
}

  


插入HTML代码:

<a href = "hello.txt">点击获取文本内容</a>

  


 2、jQuery实现ajax获取信息

这个例子是动态的从后台获取数据来改变下拉按钮的内容;

js代码以下:

function bindCarteam0(){
     //经过URL请求数据
     var URL = <select:link page="/xiaoshouwl.do?method=getCarteamList"/>;
      $.ajax({
        url:URL,
        type:'GET',
        dataType: "json",
        success:function(html){
          var str="<option value='-1'>所有</option>";
          for(var i=0;i<html.length;i++){
            str+="<option value='"+html[i].id+"'>"+html[i].name+"</option>";
          }
          $("#carteam_code").empty().html(str);
        }
      });
   }

  


HTML代码以下:

<select:select property="carteam_code" styleId="carteam_code" style="width:150px">
                     <select:option value="-1">所有</select:option>
                </select:select>
相关文章
相关标签/搜索