$(function(){
$("button").click(function (ev1) {
$.ajax({
type: "get",
url: "ajax-jquery.php",
data: {
"userName": "123",
"userPwd": "abc"
},
timeout:3000,
success: function (msg) {
alert("Data Saved: " + msg);
},
error: function (msg) {
alert(msg.status);
}
});
})
});
封装
function dataToStr(data){
data.t = new Date().getTime();
var res = [];
for(var key in data){
res.push(encodeURIComponent(key) + "=" +encodeURIComponent(data[key]));
}
return res.join("&");
}
function ajax(option) {
var str = dataToStr(option.data);
var xmlhttp,timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (option.type.toLowerCase() === 'get'){
xmlhttp.open(option.type, option.url+"?"+str, true);
xmlhttp.send();
} else{
xmlhttp.open(option.type, option.url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
xmlhttp.onreadystatechange = function (ev2) {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
option.success(xmlhttp);
} else {
option.error(xmlhttp);
}
}
}
if (option.timeout){
timer = setInterval(function(){
xmlhttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
window.onload = function (e) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev1) {
ajax({
type: "get",
url: "ajax-jquery.php",
data: {
"userName": "123",
"userPwd": "abc"
},
timeout: 3000,
success: function (msg) {
alert(msg.responseText);
},
error: function (msg) {
alert(msg.status);
}
});
}
}