我有两个函数:一个添加,另一个删除。我想重复使用相同的 ajax 调用来发送添加或删除的参数。如何优化我的功能?
这是我目前的代码
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
删除函数类似于“addData”函数,同样调用“ajaxCall”,并会发送参数删除。
我被卡住了,不知道怎么解决,希望大家能帮帮我,谢谢
最佳答案
您可以向 ajaxCall 函数添加一个新参数,并将参数作为对象发送,然后将它们与函数中的数据合并,例如:
function ajaxCall(action, params, callback) {
然后在ajax调用中:
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
事件中的调用如下:
ajaxCall("addData", {id: id, price: price}, function (error) {
关于javascript - 问题 : pass some parameters in ajax call (post),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53944063/