美文网首页
get请求和post请求方法封装()

get请求和post请求方法封装()

作者: 酒暖花深Q | 来源:发表于2018-07-16 18:03 被阅读0次

tips:配合带有 $.toast()方法的框架用,本案例用的是ligth7

get()方法

function getData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    var paramData = '';
    if (data) {
        var params = [];
        for (var key in data) {
            params.push(key + '=' + data[key]);
        }
        paramData = params.join('&');
    }
    $.ajax({
        type: 'GET',
        url: url,
        data: paramData,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (res.msg != '' && res.msg != undefined) {
                $.toast(res.msg);
            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            $.toast('请求失败');
        }
    });
}

post方法

function postData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (res.msg != '' && res.msg != undefined) {
                $.toast(res.msg);
            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            $.toast('请求失败');
        }
    });
}
var success = functoin(res){
   请求成功操作
}

用法:

 getData(url, data, success);
 ##例子
 getData('https://www.qunar.com/hotel/mustTry', {city:'wuhan'}, success);

tips:post()类似

相关文章

网友评论

      本文标题:get请求和post请求方法封装()

      本文链接:https://www.haomeiwen.com/subject/jwnbpftx.html