I'm making many ajax call based web service. I attached event listeners every dom elements. And every event handlers request ajax call in it. By the way, my source code getting more dirty and complexity. I want to reduce boilerplate code and look more simple with ajax calls.
我正在做许多基于ajax调用的web服务。我附加了事件监听器每个dom元素。每个事件处理程序都请求ajax调用。顺便说一下,我的源代码变得更加肮脏和复杂。我想减少样板代码,用ajax调用看起来更简单。
How can I do that effectively?
我怎样才能有效地做到这一点呢?
The sample code looks like this:
示例代码如下所示:
<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}));
}
});
});
Updated:
更新:
Every class name and ajax response handler is not same each other. Example code just shows boilerplate code and complexity. This is not the problem of class name or if else
statements.
每个类名和ajax响应处理程序彼此不相同。示例代码只显示样板代码和复杂性。这不是类名或if else语句的问题。
5 个解决方案
#1
5
Make common function like this:
使普通功能如下:
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();
}
}
});
}
then in your code:
然后在你的代码:
$('.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);
});
#2
3
Use a common class:
使用一个通用的类:
<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>
add listener to this class:
在这个类中添加侦听器:
$('.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}));
}
});
});
You can also use any kind of attribute and use it later for any data or parameter
您还可以使用任何类型的属性,并在以后对任何数据或参数使用它
like :
如:
<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>
and then use it for any purpose
然后把它用于任何目的
$('.button').on('click', function() {
var dVal=$(this).attr('abc');
//use dVal any where you want.
alert(dVal);
});
#3
2
You can follow this change:
你可以跟随这个变化:
<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>
Make use of data-*
attribute to hold the specific url for each link which is going to be clicked. Now just one change and you would have a common click event for all ajax calls:
使用data-*属性保存将要单击的每个链接的特定url。现在只需要一个更改就可以为所有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}));
}
});
});
As per your update in your question you can try doing this:
根据你的问题更新,你可以试着这样做:
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}));
}
}
In success you have to check if the current url of ajax call is having something different to other calls, so if that matches then you can differentiate it within the if/else if
conditions.
如果成功,您必须检查ajax调用的当前url是否与其他调用有不同之处,因此如果匹配,那么您可以在if/else if条件下对其进行区分。
#4
0
You can give a common button class to all tags and you can have a single event handler. Then on the basis of other class name you can make calls using different url and data.
您可以为所有标记提供一个公共按钮类,并且您可以拥有一个事件处理程序。然后,根据其他类名,您可以使用不同的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){
}
If you are not doing anything different then you can go for only one success function.
如果您没有做任何不同的事情,那么您只能获得一个成功函数。
#5
0
The template for anchor tag can be like this
锚标记的模板可以是这样的。
<a data-url="url" data-dataId="dataKey" data-success="functionName" onclick="ajax_call(this);">button</a>
or
或
<a href="javascript:void(0);" data-completeObj="completeObj" onclick="ajax_call(this);" class="button">button</a>
Then the javascript and jQuery part. Store all the parameters needed to pass for each request with a key, this key must match the html data attribute.
然后是javascript和jQuery部分。存储为每个请求传递一个键所需的所有参数,这个键必须与html数据属性匹配。
var myBigJsonObj = {
data1 : { "foo": "bar" },
data2 : { "foo": "bar", "foo1": "bar1"}
};
A user defined success function. Similarly can have error function.
用户定义的成功函数。同样可以有误差函数。
function success() {
// Do some stuff here
alert('Success');
}
Finally the ajax request call.
最后是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();
});
}
#1
5
Make common function like this:
使普通功能如下:
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();
}
}
});
}
then in your code:
然后在你的代码:
$('.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);
});
#2
3
Use a common class:
使用一个通用的类:
<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>
add listener to this class:
在这个类中添加侦听器:
$('.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}));
}
});
});
You can also use any kind of attribute and use it later for any data or parameter
您还可以使用任何类型的属性,并在以后对任何数据或参数使用它
like :
如:
<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>
and then use it for any purpose
然后把它用于任何目的
$('.button').on('click', function() {
var dVal=$(this).attr('abc');
//use dVal any where you want.
alert(dVal);
});
#3
2
You can follow this change:
你可以跟随这个变化:
<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>
Make use of data-*
attribute to hold the specific url for each link which is going to be clicked. Now just one change and you would have a common click event for all ajax calls:
使用data-*属性保存将要单击的每个链接的特定url。现在只需要一个更改就可以为所有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}));
}
});
});
As per your update in your question you can try doing this:
根据你的问题更新,你可以试着这样做:
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}));
}
}
In success you have to check if the current url of ajax call is having something different to other calls, so if that matches then you can differentiate it within the if/else if
conditions.
如果成功,您必须检查ajax调用的当前url是否与其他调用有不同之处,因此如果匹配,那么您可以在if/else if条件下对其进行区分。
#4
0
You can give a common button class to all tags and you can have a single event handler. Then on the basis of other class name you can make calls using different url and data.
您可以为所有标记提供一个公共按钮类,并且您可以拥有一个事件处理程序。然后,根据其他类名,您可以使用不同的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){
}
If you are not doing anything different then you can go for only one success function.
如果您没有做任何不同的事情,那么您只能获得一个成功函数。
#5
0
The template for anchor tag can be like this
锚标记的模板可以是这样的。
<a data-url="url" data-dataId="dataKey" data-success="functionName" onclick="ajax_call(this);">button</a>
or
或
<a href="javascript:void(0);" data-completeObj="completeObj" onclick="ajax_call(this);" class="button">button</a>
Then the javascript and jQuery part. Store all the parameters needed to pass for each request with a key, this key must match the html data attribute.
然后是javascript和jQuery部分。存储为每个请求传递一个键所需的所有参数,这个键必须与html数据属性匹配。
var myBigJsonObj = {
data1 : { "foo": "bar" },
data2 : { "foo": "bar", "foo1": "bar1"}
};
A user defined success function. Similarly can have error function.
用户定义的成功函数。同样可以有误差函数。
function success() {
// Do some stuff here
alert('Success');
}
Finally the ajax request call.
最后是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();
});
}