我怎样才能使许多jQuery ajax调用看起来很漂亮?

时间:2015-02-24 06:19:37

标签: javascript jquery ajax

我正在制作许多基于ajax调用的网络服务。 我为每个dom元素添加了事件监听器。每个事件处理程序都在其中请求ajax调用。 顺便说一句,我的源代码越来越脏和复杂。 我希望减少样板代码,并使用ajax调用看起来更简单。

我该如何有效地做到这一点?

示例代码如下所示:

<a href="javascript:void(0);" class="button1">button1</a>
<a href="javascript:void(0);" class="button2">button2</a>
<a href="javascript:void(0);" class="button3">button3</a>
<a href="javascript:void(0);" class="button4">button4</a>

$('.button1').on('click', function() {
    $.ajax({
        url: '/api/1/resource1',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom1').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button2').on('click', function() {
    $.ajax({
        url: '/api/1/resource2',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom2').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button3').on('click', function() {
    $.ajax({
        url: '/api/1/resource3',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom3').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button4').on('click', function() {
    $.ajax({
        url: '/api/1/resource4',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom4').html(Handlebars.resource({items:response.items}));
        }
    });
});

更新

每个类名和ajax响应处理程序彼此不相同。示例代码仅显示样板代码和复杂性。这不是类名或if else语句的问题。

6 个答案:

答案 0 :(得分:10)

使这样的共同功能:

String.prototype.endsWith = function(suffix) {
   return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var doAjax_params_default = {
    'url': null,
    'requestType': "GET",
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'dataType': 'json',
    'data': {},
    'beforeSendCallbackFunction': null,
    'successCallbackFunction': null,
    'completeCallbackFunction': null,
    'errorCallBackFunction': null,
};


function doAjax(doAjax_params) {

    var url = doAjax_params['url'];
    var requestType = doAjax_params['requestType'];
    var contentType = doAjax_params['contentType'];
    var dataType = doAjax_params['dataType'];
    var data = doAjax_params['data'];
    var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
    var successCallbackFunction = doAjax_params['successCallbackFunction'];
    var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
    var errorCallBackFunction = doAjax_params['errorCallBackFunction'];

    //make sure that url ends with '/'
    /*if(!url.endsWith("/")){
     url = url + "/";
    }*/

    $.ajax({
        url: url,
        crossDomain: true,
        type: requestType,
        contentType: contentType,
        dataType: dataType,
        data: data,
        beforeSend: function(jqXHR, settings) {
            if (typeof beforeSendCallbackFunction === "function") {
                beforeSendCallbackFunction();
            }
        },
        success: function(data, textStatus, jqXHR) {    
            if (typeof successCallbackFunction === "function") {
                successCallbackFunction(data);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            if (typeof errorCallBackFunction === "function") {
                errorCallBackFunction(errorThrown);
            }

        },
        complete: function(jqXHR, textStatus) {
            if (typeof completeCallbackFunction === "function") {
                completeCallbackFunction();
            }
        }
    });
}

然后在你的代码中:

$('.button').on('click', function() {
  var params = $.extend({}, doAjax_params_default);
  params['url'] = `your url`;
  params['data'] = `your data`;
  params['successCallbackFunction'] = `your success callback function`
  doAjax(params);
});

答案 1 :(得分:3)

使用公共类:

<a href="javascript:void(0);" class="button">button1</a>
<a href="javascript:void(0);" class="button">button2</a>
<a href="javascript:void(0);" class="button">button3</a>
<a href="javascript:void(0);" class="button">button4</a>

为此类添加侦听器:

$('.button').on('click', function() {
//find the index of the element and use it 
    var btnNumber= $( ".button" ).index(this)+1;

    $.ajax({
        url: '/api/1/resource'+btnNumber,
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom'+btnNumber).html(Handlebars.resource({items:response.items}));
        }
    });
});

您还可以使用任何类型的属性,稍后将其用于任何数据或参数

喜欢:

<a href="javascript:void(0);" abc="hello1" class="button">button1</a>
<a href="javascript:void(0);" abc="hello2" class="button">button2</a>
<a href="javascript:void(0);" abc="hello3" class="button">button3</a>
<a href="javascript:void(0);" abc="hello4" class="button">button4</a>

然后将其用于任何目的

$('.button').on('click', function() {
    var dVal=$(this).attr('abc');
//use dVal any where you want.
    alert(dVal);

});

答案 2 :(得分:2)

您可以按照以下更改:

<a href="javascript:void(0);" data-url="/api/1/resource1" class="button">button1</a>
<a href="javascript:void(0);" data-url="/api/1/resource2" class="button">button2</a>
<a href="javascript:void(0);" data-url="/api/1/resource3" class="button">button3</a>
<a href="javascript:void(0);" data-url="/api/1/resource4" class="button">button4</a>

使用data-*属性来保存要点击的每个链接的特定网址。现在只需进行一次更改,您就可以获得所有ajax调用的常见click事件:

$('.button').on('click', function() {
  var url = $(this).data('url');
  var index = $(this).index();
  $.ajax({
    url: url,
    data: {
      value1: 'value1',
      value2: 'value2'
    },
    success: function(response) {
       $('.some_dom'+index).html(Handlebars.resource({items: response.items}));
    }
  });
});

根据您在问题中的更新,您可以尝试这样做:

    success: function(response) {
       if(url.indexOf('1') != -1){
          $('.some_dom1').html(Handlebars.resource({items: response.items}));
       }else if(url.indexOf('2') != -1){
          $('.some_dom2').html(Handlebars.resource({items: response.items}));
       }else if(url.indexOf('3') != -1){
          $('.some_dom3').html(Handlebars.resource({items: response.items}));
       }
    }

成功之前,你必须检查ajax调用的当前url是否与其他调用有所不同,所以如果匹配,那么你可以在if/else if条件下区分它。

答案 3 :(得分:0)

您可以为所有标记提供一个通用按钮类,您可以拥有一个事件处理程序。然后根据其他类名称,您可以使用不同的URL和数据进行调用。

<a href="javascript:void(0);" class="button button1">button1</a>
<a href="javascript:void(0);" class="button button2">button2</a>
<a href="javascript:void(0);" class="button button3">button3</a>
<a href="javascript:void(0);" class="button button4">button4</a>


var  ajaxFunc = function(url, data, successFun){
     $.ajax({
        url: url,
        data:data,
        success: successFun
    });
}

$('button').on('click', buttonClick);


function buttonClick (){
    var elem = $(event.target),
        url='', data;
    if(elem.hasClass('button1')){
        url = '/api/1/resource1';
        data =  {
            value1: 'value1',
            value2: 'value2'
        }
        ajaxFunc(url, data, successFun1);
    } else if(elem.hasClass('button2')){
        url = '/api/1/resource2';
        data =  {
            value1: 'value1',
            value2: 'value2'
        }
        ajaxFunc(url, data, successFun2)
    } else if(elem.hasClass('button3')){
        url = '/api/1/resource3';
        data =  {
            value1: 'value1',
            value2: 'value2'
        }
        ajaxFunc(url, data, successFun3)
    }
     else if(elem.hasClass('button4')){
        url = '/api/1/resource4';
        data =  {
            value1: 'value1',
            value2: 'value2'
        }
        ajaxFunc(url, data, successFun4)
    }
}

function successFun1(evt){

}
function successFun2(evt){

}

如果你没有做任何不同的事情,那么你只能选择一个成功函数。

答案 4 :(得分:0)

锚标记的模板可以是这样的

<a data-url="url" data-dataId="dataKey" data-success="functionName" onclick="ajax_call(this);">button</a>

<a href="javascript:void(0);" data-completeObj="completeObj" onclick="ajax_call(this);" class="button">button</a>

然后是javascript和jQuery部分。 使用密钥存储为每个请求传递的所有参数,此密钥必须与html数据属性匹配。

var myBigJsonObj = { 
    data1 : { "foo": "bar" }, 
    data2 : { "foo": "bar", "foo1": "bar1"}                   
};

用户定义的成功功能。同样可以有错误功能。

function success() {
    // Do some stuff here
    alert('Success');
}

最后是ajax请求调用。

function ajax_call(obj) {
    var url = obj.getAttribute('data-url');
    var data = myBigJsonObj[obj.getAttribute('data-dataID')];
    var success = obj.getAttribute('data-success');

    $.ajax({
        url: url,
        data: data,
        success: window[success].call();
    });
}

答案 5 :(得分:0)

您可以创建一个包含 ajax API 调用的异步函数。然后从任何地方,您都可以简单地调用和使用“then”方法来实现成功和错误响应。

就像这里我会给你一个非常基本的例子:

    public function subUsersUpdate(Request $request, $id) {
        $will = Will::where('id', $id)->where('user_id', Auth::id())->first();
        $user = User::where('id', $will->user_id)->first();
        $userMail = substr($user->email, 0, strpos($user->email, '@'));
        $websiteName = env('DOMAIN_NAME');
    
    
        //Changed part
        $mails = $request->input('mails');
        $names = $request->input('subs');
    
        // created array of data
        $finalInputs = [];
        foreach($mails as $index => $mmm) {
            foreach($names as $index2 => $nnn) {
                $finalInputs[$index] = ['email' => $mmm, 'name' => $nnn];
            }
        }
    
        foreach($finalInputs as $index => $sub) {
            if(!empty($sub['email'])) {
                $existedUser = User::where('email', $sub['email'])->where('user_id', $user->id)->first();
                $existedUser->update(['name' => $sub['name']]);
                // $userMail2 = substr($sub['email'], 0, strpos($sub['email'], '@'));
            } else {
                if($sub['name'] != null) {
                    $num = $index+1;
                    $password = str_random(15);
                    User::create([
                        'name' => $sub['name'],
                        'email' => $userMail . $num ."@" . $websiteName,
                        'password' => Hash::make($password),
                        'user_id' => $user->id,
                    ]);
                }
            }
        }
        // end of changed parts
    }

然后从任何需要以异步方式使用此ajax调用的地方,例如:

// req is JSON type
// SERVICE_URL is global declared service URL or you can pass it as an argument

async function apiCall(req) {
    var form_data = new FormData;
    for (var key in req) form_data.append(key, req[key]);

    let myPromise = new Promise(function (myResolve, myReject) {
        $.ajax({
            url: SERVICE_URL,
            type: 'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function (result) {
                myResolve(result);
            },
            error: function (error) {
                myReject(error);
            }
        });
    });

    return await myPromise;
}

这是一个完全异步的实现,因为它是一个通用函数,因此是一种最简洁的方法。

如果你喜欢这个解决方案,请点赞。谢谢!