Ajax的open函数形式为open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword),其中的bstrMethod通常有GET和POST两种常用方式,使用get方式需要注意:
1 对于get请求(或凡涉及到url传递参数的),被传递的参数都要先经encodeURIComponent方法处理.例:var url = "update.php?username=" +encodeURIComponent(username) + "&content=" +encodeURIComponent
(content)+"&id=1" ;
使用Post方式需注意:
1.设置header的Context-Type为application/x-www-form-urlencode确保服务器知道实体中有参数变量.通常使用XmlHttpRequest对象的SetRequestHeader("Context-Type","application/x-www-form-urlencoded;")。例:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2.参数是名/值一一对应的键值对,每对值用&号隔开.如 var name=abc&sex=man&age=18,注意var name=update.php?
abc&sex=man&age=18以及var name=?abc&sex=man&age=18的写法都是错误的;
3.参数在Send(参数)方法中发送,例: xmlHttp.send(name); 如果是get方式,直接 xmlHttp.send(null);
4.服务器端请求参数区分Get与Post。如果是get方式则$username = $_GET["username"]; 如果是post方式,则$username = $_POST["username"];
以下是自己测试open函数的js代码:
var xmlHttp;
//创建xmlHttpRequest对象
function createXMLHttpRequest(){
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
//发送参数字符串
function createQueryString(){
//得到姓
var firstName = document.getElementById("firstName").value;
//得到中间名
var middleName = document.getElementById("middleName").value;
//得到生日
var birthday = document.getElementById("birthday").value;
//构造请求字符串
var quertString = "firstName=" + firstName + "&middleName=" + middleName
+ "&birthday=" + birthday;
return quertString;
}
//处理GET请求
function doRequestUsingGET(){
createXMLHttpRequest();
var queryString = "ajaxForm?";
queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET",queryString,true);
xmlHttp.send(null);
}
//处理POST请求
function doRequestUsingPOST(){
createXMLHttpRequest();
var url = "ajaxForm?"+createQueryString()+"&timeStamp=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xmlHttp.send(null);
}
//回调方法
function handleStateChange(){
if (xmlHttp.readyState == 4){
if (xmlHttp.status == 200){
//解析返回结果
parseResults();
}
}
}
//解析返回结果
function parseResults(){
var responseDiv = document.getElementById("serverResponse");
if (responseDiv.hasChildNodes()){
responseDiv.removeChild(responseDiv.childNodes[0]);
}
//返回文本构造一个文本节点
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}