ES6系列---【ES6中利用解构赋值实现ajax封装】

将封装函数保存为外部js, 需要时引用:

  // 利用解构赋值实现ajax封装函数。可灵活使用解构赋值的默认值,这样调用函数时只需要传递必要的参数即可
  function sendAjax({type="get",url,data=null,dataType="json",timeOut="5000"},callback) {
    $.ajax({
      type: type, //请求的方法 get post
      url: url,  //请求的地址
      data: data, // 请求时发送的数据
      dataType: dataType, //期望返回的数据类型
      // ajax成功后的回调函数
      success: function (response) {
        // console.log(respnse);
        callback(response)
      },
      // 失败时的回调函数
      error: function (err) {
        console.log(err);
      }
    });
  }
<script src="./sendAjax.js"></script>
<script>
sendAjax({type:"post",url:"http://api.shenzhou888.com.cn/v2/ecapi.banner.list"},function(data){
    // 渲染页面代码
    console.log( data );
  });
</script>
原文地址:https://www.cnblogs.com/chenhaiyun/p/14655112.html