[英]Handling multiple Ajax requests
我正在开发一个需要多个ajax请求的应用程序,这样Option2
只有在点击Button2
并返回其响应时才可用。 同样,只有在单击Button3
时, Option3
才可用。 以下是代码的一般结构。 我在php
和mysql
构建应用程序。
$("#button1").click(function() {
$.ajax({
type: "POST",
url: "url-1",
data: { id: //some-id },
success: function(response) {
$('.menu-right').html(response);
$(".button2").click(function() { //button2 is created when the above response is printed as html
$.ajax({
type: "POST",
url: "url-2",
data: { id: this.id },
success: function(response) {
$('.menu-right-jump').html(response);
$('.button3').click(function() { ////button3 is created when the above response is printed as html
$.ajax({
type: "POST",
url: "url-3",
data: { id: this.id },
success: function(response) {
// some things to do
},
error: function(error) {
alert("Error");
}
});
});
},
error: function(error) {
alert("Error");
}
});
});
},
error: function(error) {
alert("Error");
}
});
});
目前,一切正常。 该应用程序最多可容纳10,000名用户。 我只是想知道是否有更好的方法来实现这个/或任何我可以合并的框架。
另外:使用这种方式可能出现的问题以及清除这些问题的方法。
使用jQuery有一种更简洁的方法。 使用.ready
函数。
$("#button1").click(function() {
$.ajax({
type: "POST",
url: "url-1",
data: { id: //some-id },
success: function(response) {
$('.menu-right').html(response);
},
error: function(error) {
alert("Error");
}
});
});
//When I'm ready... provide a click event
$(".button2").ready(function(){
$(".button2").click(function() { //button2 is created when the above response is printed as html
$.ajax({
type: "POST",
url: "url-2",
data: { id: this.id },
success: function(response) {
$('.menu-right-jump').html(response);
},
error: function(error) {
alert("Error");
}
});
});
});
$(".button2").ready(function(){
$('.button3').click(function() { ////button3 is created when the above response is printed as html
$.ajax({
type: "POST",
url: "url-3",
data: { id: this.id },
success: function(response) {
// some things to do
},
error: function(error) {
alert("Error");
}
});
});
});
以你的方式做到的问题。 由于nesting
太多(例如,如果你需要增加4个按钮),它也可能导致技术债务,这是很难维护的。
避免创建深层嵌套的if-then语句,因为它们更难以阅读且易于维护。 资源
你可以更进一步,更好地将每个ajax请求封装到一个单一函数中并编写自己的jQuery callback
。
你也可以使用jquery的.on
功能来嵌套那些
$('body').on('click' ,'.button2', doButton2request);
$('body').on('click' ,'.button3', doButton3request);
$("#button1").click(doButton1request)
function doButton1request()
{
do ajax and on success put in the new button
}
function doButton2request()
{
do ajax and on success put in the new button
}
function doButton3request()
{
do ajax and on success do "some things to do"
}
on函数连接事件,以便每当有人点击任何内容时(在'body'内),如果该类是.button2,则它调用该函数(this)作为匹配的项。 您可以根据需要添加和删除按钮或.button2类。 也可以使用.off,你可以暂时停止这些事件的发射。
因此,一般的想法是,只要您有可在应用开始时不存在的可点击项目,您就可以设置.on事件。 或者,在添加了另一个类之前,您可以拥有不会获得点击的项目,例如“.active”或其他类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.