zoukankan      html  css  js  c++  java
  • 简单封装一个ajax插件

    function ajax(options){
    //创建一个ajax对象
    var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft,XMLHTTP");
    //数据的处理 {a:1,b:2} a=1&b=2;
    var str = "";
    for(var key in options.data){
    str+="&"+key+"="+options.data[key];
    }
    str = str.slice(1);
    if(options.type === "get"){
    var url = options.url+"?"+str;
    xhr.open("get",url);
    xhr.send();
    }else if(options.type === "post"){
    xhr.open("post",options.url);
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
    xhr.send(str)
    }
    //监听
    xhr.onreadystatechange = function(){
    //当请求成功的时候
    if(xhr.readyState === 4 && xhr.status === 200){
    var d = xhr.responseText;
    //将请求的数据传递给成功回调函数
    options.success&&options.success(d)
    }else if(xhr.status !== 200){
    //当失败的时候将服务器的状态传递给失败的回调函数
    options.error&&options.error(xhr.status);
    }
    }
    }

    // 如何调用:
    ajax({
    type:'get',
    url:'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/cats_distinguish',
    data:{},
    success:function (data) {
    console.log(data)
    }
    })


  • 相关阅读:
    web页面静态化与伪静态化
    mysql 优化之空间换时间
    QPS、PV、UV、RT 之间的关系
    接口
    MySQL 索引
    名词解释
    go 语言标识符
    Git版本控制与工作流
    Maven安装与配置
    IDEA工具使用说明
  • 原文地址:https://www.cnblogs.com/yang656/p/10336003.html
Copyright © 2011-2022 走看看