Ajax(二):技术实现

Ajax(二):技术实现

一.若没有Ajax时,一般的表单提交代码为:

客户端代码

<form id="form1" action="Test.ashx" method="get">
   您的姓名1<input type="text" name="fname" size="20" />
   <input type="submit" name="submit" value="Sumbit">
</form>

服务端代码

public void ProcessRequest (HttpContext context)
{
  //Delay
  for (int i = 0; i < 2; i++)
  {
   System.Threading.Thread.Sleep(1000);
  }
  
   //从Requset.Form中获取fname的值。使用Form获取请求的键值对的值的前提条件是HTTP request Content-Type 值必须是"application/x-www-form-urlencoded" 或 "multipart/form-data".
  string fname = context.Request["fname"];
  
  context.Response.ContentType = "text/plain";
 //将字符串写入 HTTP 响应输出流。
  context.Response.Write("Hello World " + fname);
   }

此时的工作流程为:
在这里插入图片描述
二.Ajax代码:

客户端代码:

<!DOCTYPE html>
  
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta charset="utf-8" />
 <title></title>
 <script type="text/javascript" src="Ajax.js"></script>
  
</head>
<body>
 <div id="Test" style="background-color:#40eeee">
  您的姓名2<input type="text" id="testGetName" size="20" />
  <button type="button" onclick="testGet();">Ajax Get请求</button>
 </div>
    
 <div id="Test" style="background-color:#ff6a00">
  您的姓名3<input type="text" id="testPostName" size="20" />
  <button type="button" onclick="testPost();">Ajax Post请求</button>
 </div>
  
 <div id="myDiv" />
  
</body>
</html>

客户端JS代码

var xmlhttp = createRequest();
  
function testGet() {
 var fname = document.getElementById("testGetName").value;
 xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random() , true);
 xmlhttp.onreadystatechange = callback;
 xmlhttp.send(null);
}
  
function testPost() {
 var fname = document.getElementById("testPostName").value;
 xmlhttp.open("POST", "Test.ashx?" + "&random=" + Math.random() , true);
 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
 xmlhttp.onreadystatechange = callback;
 xmlhttp.send("fname="+fname);
  
}
  
function createRequest() {
 var xmlhttp;
 if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
 }
 else {
  // code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xmlhttp
}
  
function callback() {
 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
 }
}

此时的工作流程为:在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值