ajax正确的简单封装“姿势”

时间:2021-05-19 12:38:38
 window.meng = window.meng || {};
 (function ($) {
     function getAjaxDate(url, apikey) {
         var datas;
         $.ajax({
             url: url,
             headers: {"apikey": apikey},
             async: false,
             success: function (data) {
                 datas = data;
             },
             error: function (data) {
                 console.log("error !");
             }
         });
         return datas;
     }

     meng.getAjaxDate = getAjaxDate;
 })(jQuery);

注意:设置async:false 即同步

主函数调用的时候:

 window.meng = window.meng || {};
 (function ($) {

     var url = "http://apis.baidu.com/tngou/cook/name?name";
     var apikey = "1234567890";
     var data = meng.getAjaxDate(url, apikey);
     console.log(data);

 })($);