js和jQuery中ajax的重要步骤

js中:

function ajax(method,url,callBack,data,flag){

var xhr = null; 

if(window.XMLHttpRequest){

xhr = new XMLHttpRequest;

}else{

xhr = new ActiveXObject('Microsoft.XMLHttp');

}

method = method.toUpperCase();

if(method == "GET"){

xhr.open(method,url+"?"+data,flag);

xhr.send();

}else if(method == "POST"){

xhr.open(method,url,flag);

xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');

xhr.send(data);

}

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

// xhr.responseText //返回回来的值

callBack(xhr.responseText);

}

}

}

}

jQuery中:

get方法:

$.ajax({//jq自带的方法

type:"get",//请求的类型 get post

url:"ajax01.php?username=" + $("#uname").val(),//传输的地址

async:true,//是否异步,默认为true异步

success:function(data){//成功后后台返回来的信息

console.log(data)

if(data == 1){

$("#uname-msg").html("该用户名是占用状态").css("color","red");

}else if(data == 0){

$("#uname-msg").html("该用户名是可用状态").css("color","green");

}

},

error:function(xhr){

alert("发送错误" + xhr.status)

}

});

post方法:

$.ajax({

type:"post",

url:"ajax02.php",

data:{

"stuname" : "tom",

"stuage" : "18"

},

async:true,

success:function(data){

console.log(data)

},

error:function(xhr){

}

});

原文地址:https://www.cnblogs.com/hyh888/p/11687998.html