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);
  });
原文地址:https://www.cnblogs.com/gyfluck/p/12836188.html