原生Ajax jquery中使用Ajxa

Ajax (Asynchronous JavaScript and Xml)(异步jsxml

Ajax的本质是什么:

交互式的,快速动态开发网页技术

本质是发送请求与接收请求

ajax提供了与服务器的异步通信,在请求发送后可以查询或更新数据库,在请求返回后可以更新页面的局部内容

Ajax的标准格式:

GET

xmlhttp = new XMLHttpRequest();

//异步执行函数

xmlhttp.onreadystatechange=function()

{

    if (xmlhttp.readyState==4 && xmlhttp.status==200)

    {

        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    }

}

xmlhttp.open("GET","target.php?tid=1",true);

xmlhttp.send();

//open里面函数值分别是“传值方式”、“目标网页”、“是否异步”,send中不用写任何东西

  

Post

xmlhttp = new XMLHttpRequest();

//异步执行函数

xmlhttp.onreadystatechange=function()

{

    if (xmlhttp.readyState==4 && xmlhttp.status==200)

    {

        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    }

}

xmlhttp.open("POST","target.php",true);

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send("user_id="+getCookie("user_id")+"&"+"user_pwd="+getCookie("user_pwd"));

 

  

注意点:

1.POST第二行要设置响应头,固定的!!!!!!

2.POST发送的数据用&隔开,千万不能用错,虽然传送的是cookie值,但并不是直接将cookie写上去(cookie是用分号隔开)

3.在服务器那边的php直接就能用$_POST["user_id"]来获取数据(好久才跳出来的坑)

4.xmlhttp.onreadystatechange()函数是异步执行的,要等到服务器返回了数据才执行,所以书写在哪里都行,使用该函数的前提是是否异步true

5.如果是否异步false,则需要将xmlhttp.onreadystatechange()函数写在xmlhttp.send()后面

1、使用ajax发送数据的步骤

第一步:创建异步对象

var xhr = new XMLHttpRequest();

第二步:设置 请求行 open(请求方式,请求url):

// get请求如果有参数就需要在url后面拼接参数,

// post如果有参数,就在请求体中传递 xhr.open("get","validate.php?username="+name)

xhr.open("post","validate.php");

第三步:设置请求(GET方式忽略此步骤)头:setRequestHeader()

// 1.get不需要设置

// 2.post需要设置请求头:Content-Type:application/x-www-form-urlencoded

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

第四步:设置请求体 send()

// 1.get的参数在url拼接了,所以不需要在这个函数中设置

// 2.post的参数在这个函数中设置(如果有参数)

xhr.send(null) xhr.send("username="+name);

第五步:让异步对象接收服务器的响应数据

// 一个成功的响应有两个条件:1.服务器成功响应了 2.异步对象的响应状态为4(数据解析完毕可以使用了)

xhr.onreadystatechange = function(){

if(xhr.status == 200 && xhr.readyState == 4){

 console.log(xhr.responseText);

 }

Jquery使用ajax

$.ajax({

 type:"get",// get或者post

 url:"abc.php",// 请求的url地址

 data:{},//请求的参数

 dataType:"json",//json写了jq会帮我们转换成数组或者对象 他已经用JSON.parse弄好了

 timeout:3000,//3秒后提示错误

 beforeSend:function(){

 // 发送之前就会进入这个函数

 // return false 这个ajax就停止了不会发 如果没有return false 就会继续

 },

 success:function(data){ // 成功拿到结果放到这个函数 data就是拿到的结果

 },

 error:function(){//失败的函数

 },

 complete:function(){//不管成功还是失败 都会进这个函数

 }

})

// 常用

$.ajax({

 type:"get",

 url:"",

 data:{},

 dataType:"json",

 success:function(data){

 }

})

ajax返回的格式的数据由后台处理,一般都是json格式进行交互

如果需要对数据加密,可以重写jquery中的ajax函数,或者在添加参数前先加密,后台在进行解密。

猜你喜欢

转载自www.cnblogs.com/wjune-0405/p/12441956.html