首页 > Web开发 > 详细

js和jQuery中ajax的重要步骤

时间:2019-10-16 23:07:12      阅读:78      评论:0      收藏:0      [点我收藏+]

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){

}

});

 

js和jQuery中ajax的重要步骤

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!