1.GET
function getdate() {
var request = new XMLHttpRequest();
request.open("GET", "/http/index/getdata?name=brell");
request.send();
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
alert(request.responseText);
} else {
alert("发生错误:" + request.status);
}
}
}
}
2.POST
function postdata() {
var request = new XMLHttpRequest();
request.open("POST", "doAction.php");
var data = "name=" +"brell"
+ "&sex=" + "boy"
+ "&job=" + "PHP";
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
alert(request.responseText);
} else {
alert("发生错误:" + request.status);
}
}
}
}
3.JSON形式处理数据
document.getElementById("search").onclick = function() {
var request = new XMLHttpRequest();
request.open("GET", "、index/index/json?number=" + document.getElementById("keyword").value);
request.send();
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
var data = JSON.parse(request.responseText);
if (data.success) {
document.getElementById("searchResult").innerHTML = data.msg;
} else {
document.getElementById("searchResult").innerHTML = "出现错误:" + data.msg;
}
} else {
alert("发生错误:" + request.status);
}
}
}
}
document.getElementById("save").onclick = function() {
var request = new XMLHttpRequest();
request.open("POST", "/index/index/postjson");
var data = "name=" + document.getElementById("staffName").value
+ "&sex=" + document.getElementById("staffSex").value;
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function() {
if (request.readyState===4) {
if (request.status===200) {
var data = JSON.parse(request.responseText);
if (data.success) {
document.getElementById("createResult").innerHTML = data.msg;
} else {
document.getElementById("createResult").innerHTML = "出现错误:" + data.msg;
}
} else {
alert("发生错误:" + request.status);
}
}
}
}