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);
      });
  • 相关阅读:
    Web开发细节搜集
    excel设置单元格为文本
    网页QQ唤起
    .net提高文章
    代码重构学习
    js的undefined怎么判断
    微软.net一些类的源码
    FineMessBox的js依赖导致错误Uncaught ReferenceError: addEvent is not defined
    [译转]深入理解LayoutInflater.inflate()
    java 和 Android Base64加密
  • 原文地址:https://www.cnblogs.com/gyfluck/p/12836188.html
Copyright © 2011-2022 走看看