分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

Ajax异步请求几步曲——可直接引入

发布时间:2023-09-06 01:13责任编辑:白小东关键词:Ajax异步请求

引入函数ajax(method,url,postStr,dataType="json"){

  return new Promise((resolve,reject)=>{...}

)};

function ajax(method,url,postStr,dataType="json"){ ?return new Promise((resolve,reject)=>{

method: 请求方式,string类型,常取值:get   post...

url:请求地址,string类型

postStr:当method取post时需要发送给服务端的数据字符串

dataType:响应消息头,默认json,告诉浏览器是什么格式以及什么类型

1.获取xhr

var xhr = function(){
  if(window.XMLHttpRequest){
    return new XMLHttpRequest();
  }else{
    return new ActiveXObject("Microsoft.XMLHttp")
  }
}

 2.创建请求

  xhr.open(method,url,true); 

 3.设置请求消息头

如果method取值为post,则需修改消息头

if(method=="post"){ ?????xhr.setRequestHeader( ???????"Content-Type", "application/x-www-form-urlencoded"); ???}

  

4.设置回调并发送

xhr.onreadystatechange = function(){
  if(xhr.readyState==4){
    if(xhr.status==200){
      if(url.indexof(".php")!=-1&&dataType.toLowerCase()=="json"){
        console.log(xhr.responseText);
        resolve(JSON.parse(xhr.responseText)); 
      }else{
        console.log(xhr.responseText);
        resolve(xhr.responseText);
      }
    }else{
        reject("ajax出错了"+xhr.status);
    }
  }
  xhr.send(postStr);
}

  完整代码如下,服务器PHP,用JSON解析,不同的可以相应改动一下。

 1 function ajax(method,url,postStr,dataType="json"){ ?// 2 ??return new Promise((resolve,reject)=>{ 3 ????//1、获取 xhr 4 ????var xhr = (function(){ 5 ??????if(window.XMLHttpRequest){ 6 ????????return new XMLHttpRequest(); 7 ??????}else{ 8 ????????return new ActiveXObject("Microsoft.XMLHttp"); 9 ??????}10 ????})();11 ????//2、创建请求12 ????xhr.open(method,url,true);13 ????14 ????//4、设置请求消息头15 ????if(method=="post"){16 ??????xhr.setRequestHeader(17 ????????"Content-Type", "application/x-www-form-urlencoded");18 ????}19 ????//3、设置回调20 ????xhr.onreadystatechange=function(){21 ??????if(xhr.readyState == 4)22 ????????if(xhr.status == 200){23 ??????????if(url.indexOf(".php")!=-124 ????????????&&dataType.toLowerCase()=="json"){25 ????????????console.log(xhr.responseText);26 ????????????resolve(JSON.parse(xhr.responseText));27 ??????????}else{28 ????????????console.log(xhr.responseText);29 ????????????resolve(xhr.responseText);30 ??????????}31 ????????}else32 ??????????reject("ajax出错啦!"+xhr.status);33 ????}34 ????//5、发送35 ????xhr.send(postStr);36 ??})37 }

Ajax异步请求几步曲——可直接引入

原文地址:http://www.cnblogs.com/tanghm/p/7580885.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved