【发布时间】:2019-05-25 10:12:09
【问题描述】:
我有 2 个功能:一个要添加,另一个要删除。我想重用相同的 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”,会发送参数删除。
我被卡住了,不知道怎么解决,希望大家帮帮我,谢谢
【问题讨论】:
-
在会话中添加一个布尔参数来标识调用的类型(addData或removeData)
标签: javascript jquery ajax click call