Ajax清晰请求步骤与代码

编程入门 行业动态 更新时间:2024-10-25 22:34:48

Ajax清晰请求<a href=https://www.elefans.com/category/jswz/34/1771434.html style=步骤与代码"/>

Ajax清晰请求步骤与代码

 

异步请求ajax的使用在前后台传递数据,优化用户体验起着至关重要的角色,那么下面给大家简单罗列了一下ajax请求的步骤与代码。

一、原生JS中的Ajax:

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);}

ajax-get方式请求案例:

var xhr = new XMLHttpRequest();
xhr.open("get","validate.php?username="+name);
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){ console.log(xhr.responseText); document.querySelector(".showmsg").innerHTML = xhr.responseText;;}}

ajax-post方式请求案例:

var xhr = new XMLHttpRequest();
xhr.open("post","validate.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+name);
xhr.onreadystatechange = function(){
// 判断服务器是否响应,判断异步对象的响应状态
if(xhr.status == 200 && xhr.readyState == 4){document.querySelector(".showmsg").innerHTML = xhr.responseText;}}

二、Jquery中的Ajax

$.ajax({type:"get",// get或者posturl:"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() 都可以发

$.post(url,data,success,datatype):本质上只能发送post请求

$.get(url,data,success,datatype):本质上只能发送get请求

更多推荐

Ajax清晰请求步骤与代码

本文发布于:2023-06-12 05:15:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/651995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:步骤   清晰   代码   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!