zoukankan      html  css  js  c++  java
  • 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")!=-1
    24             &&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         }else
    32           reject("ajax出错啦!"+xhr.status);
    33     }
    34     //5、发送
    35     xhr.send(postStr);
    36   })
    37 }
  • 相关阅读:
    软件策划书
    对开发团队的看法
    对敏捷开发的认识
    企业单位
    Pg数据库的基础安装
    Windows Server 任务计划执行.exe
    2020.04.08 重新开始
    20200211 Oracle监听启动异常
    20191225 医疗行业数据仓库
    20191224 多维数据库
  • 原文地址:https://www.cnblogs.com/tanghm/p/7580885.html
Copyright © 2011-2022 走看看