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");
}
或者:
xmlhttp=new XMLHttpRequest()||ActiveXObject("Microsoft.XMLHTTP");
GET请求:
function ajax(){
var xml=new XMLHttpRequest()||ActiveXObject("Microsoft.XMLHTTP");
xml.onreadystatechange=function(){
if (xml.readyState==4&&xml.status==200){
document.getElementById("myDiv").innerHTML=xml.responseText;
}
}
xml.open("get","/ajax_info.txt?t="+ Math.random(),true);
xml.send();
}
post请求 如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
var jsondata='{staff:[{"name":"洪七","age":"70"},{"name":"郭靖","age":"35"},{"name":"黄蓉","age":"30"}]}';
//容易解释执行语句,不考虑字符串是否合法。
var jsonobj=eval('('+jsondata+')');
alert(jsonobj.staff[0].name);
//推荐使用
var jsonobj_2=JSON.parse(jsondata);