合并在两个独立事件上运行的两个Ajax请求



我使用以下代码发送两个ajax请求。一种是加载默认内容的页面加载发送,另一种是用于按钮,因此如果用户单击某个按钮,则会根据该按钮更改内容。

我想知道是否有一种方法可以简化下面的代码。任何意见都将不胜感激。

< script >
$(document).ready(function() {
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
data: 'default',
cache: false,
success: function(html) {
$("#responsecontainer").html(html);
alert(response);
}
});

});
$(".myclass").click(function() {
var value = $(this).attr('value');
console.log(value);
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
data: '&type=' + value,
cache: false,
success: function(response) {
$("#responsecontainer").html(response);
alert(response);
}
});
}); <
/script>

考虑以下内容。

$(function() {
function getContainerData(myData) {
$.ajax({
type: "POST",
url: "filter.php",
dataType: "html",
data: myData,
cache: false,
success: function(html) {
$("#responsecontainer").html(html);
console.log(html);
}
});
}
getContainerData("default");
$(".myclass").click(function(event) {
getContainerData('&type=' + $(this).attr("value"));
});
});

这创建了一个函数,允许您输入要在AJAX调用中传递的特定数据。

您可以考虑传入一个Object。

{ type: "default" }

{ type: $(this).attr("value") }

AJAX会将其转换为正确的POST值。

最新更新