您的位置:首页 > 理论基础 > 计算机网络

详解AJAX核心 —— XMLHttpRequest 对象 (下)

2014-06-12 20:18 369 查看
继续上一篇的内容
上一篇关于XMLHttpRequest 对象发送对服务器的请求只说到了用Get方式,没有说Post方式的。那是因为要说Post方式就需要先说另外一个东西,那就是DOM(Document Object Model)文档对象模型。JavaScript通过DOM读取、改变或者删除 HTML、XHTML 以及 XML中的元素,可以重构整个 HTML 文档。可以添加、移除、改变或重排页面上的项目,而且这样的操作会马上显示在页面上。另外,所有浏览器执行W3C 发布的 DOM 标准规范,DOM的跨浏览器的兼容问题也就不是问题了。

先来看看下面的这个HTML文档

<html>
<head>
<title>AJAX and the DOM</title>
<script language="JavaScript">
var xmlhttp = false; //创建一个新变量 request 并赋值 false。使用 false 作为判断条件,它表示还没有创建 XMLHttpRequest 对象。
function CreateXMLHttp(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //较新版本的IE
if(!xmlhttp) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //较旧版本的IE
}
}
return xmlhttp;
}
xmlhttp = CreateXMLHttp();

function send()
{
xmlhttp.open("Post","http://localhost/WebForm1.aspx",true);
var name = document.getElementById("name").value; //取名字
var age = document.getElementById("age").value;  //取年龄
var info = name+"|"+age; //简单的将姓名和年龄用竖线分割交给服务器处理
var result = document.getElementById("result").firstChild;
xmlhttp.send(info);
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4 && newxmlhttp.status == 200){
result.nodeValue = newxmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<div id="Content">
<input type="text" id = "name" value="myname" />
<br/>
<input type="text" id = "age" value="99" />
</div>
<input type="button" value="Test me!" onClick="send();" />
<div id = "result"></div>
</body>
</html>

服务器端就做最近简单的处理,代码如下:



<%@ Page language="c#" AutoEventWireup="true" %>
<script language="C#" runat="server">
public string result;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
System.IO.StreamReader sr = new System.IO.StreamReader(Page.Request.InputStream,System.Text.Encoding.UTF8);
string[] gets = sr.ReadToEnd().Split('|');
result = string.Format(@"Your name is {0},{1} years old!",gets[0],gets[1]);
}
</script>
<%=result%>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: