最基础的Ajax

还是把这篇比较基础的文章写下来吧,不然以后会像我现在忘掉c#一样被忘记。

最基础的Ajax,可以异步调用同域的数据。

基于已被和谐的译言网上的一篇文章,加了些注释。

<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari/IE8/Opera
if (window.XMLHttpRequest) { 
    self.xmlHttpReq = new XMLHttpRequest();
}
// IE7-
else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);//Post方式请求数据
//若是post方式必须有下面这句话
self.xmlHttpReq.setRequestHeader('Content-Type',
//'application/x-www-form-urlencoded'表示请求方式为字典型,即许多对“x=y”似的数据。
//若上传数据,则使用'multipart/form-data',在服务器端(asp.net)要用Response.InputStream调用,也可以用此方法传递xml。  
    'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
//readyState==4:已经收到数据
//readyState==3:正在解析数据
//readyState==2:正在接收数据
//readyState==1:正在发送请求
//readyState==0:正在初始化
//status==200:http ok
//status==404:not found
//status==500:server error
if (self.xmlHttpReq.readyState == 4&&self.xmlHttpReq.status==200) {//已经收到数据
    updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
//记得要用escape函数编码
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
//若有多个数据用'&'连接
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>

<body>
<form name="f1">
<p>word: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax-example.cgi")'></p>
<div id="result"></div>
</form>
</body>
</html>

CGI脚本就不写了。

发表评论