zoukankan      html  css  js  c++  java
  • ajax请求

    /**
     * 发送ajax请求
     * @param  {string}   api_url    [请求接口]
     * @param  {object}   req_data   [请求参数]
     * @param  {string}   req_method [请求方式]
     * @param  {Function} callback   [回调函数]
     * @return {boolean|string|object}   [请求结果]
     */
    function req_api_data(api_url,req_data,req_method,callback){
      if(typeof api_url == 'undefined' || api_url == ''){
        alert('错误的请求地址');
        return false;
      }else if(typeof req_data == 'undefined'){
        alert('错误的请求参数');
        return false;
      }else if(typeof req_method == 'undefined' || (req_method != 'get' && req_method != 'post')){
        alert('错误的请求方式');
        return false;
      }
        
      if(req_method == 'post'){
        req_data = JSON.stringify(req_data);
      }
      $.ajax({
        url:api_url,
        type:req_method,
        dateType:'json',
        async:true,
        beforeSend: function(xhr) {
          xhr.setRequestHeader("id", 'xxx');//可以增加设置请求头参数
          xhr.setRequestHeader("name",'xxx');//可以增加设置请求头参数
        },
        headers:{
          'Content-Type':'application/json;charset=utf8',//修改请求头参数
        },
        data:req_data,
        success:function(data){
          if(data.code == 200){
            callback(data);
          }else{
            alert(data.msg);
          }
        },error:function(data){
          alert('服务器异常错误,请稍后再试');
        }
      });
    }
    
    //示例
      req_api_data('https://www.test.com/Api/test',{'id':1},'get',function(req_result){
            console.log(req_result);
      });
  • 相关阅读:
    android-基础编程-RecyclerView
    android-基础编程-ListView
    LINUX 日志服务器的搭建
    使用parted进行磁盘分区
    raid磁盘阵列
    LVM逻辑卷管理
    /home 分区迁移试验
    PHP 匹配一个汉字
    xhr dojo load
    ERR: Call to undefined function openssl_random_pseudo_bytes()
  • 原文地址:https://www.cnblogs.com/gyfluck/p/12836188.html
Copyright © 2011-2022 走看看