如果 ajax 失败,我想返回按钮值。
此 HTML(在 PHP 上):
<a href="javascript:void(0);" id="follow-topic" value="7">
<button class="btn btn-xs btn-primary pull-right"><?php echo $_LANGS['forum']['follow']; ?></button>
</a>
这个 JS(在 PHP 上):
$("#follow-topic").click(function(event) {
var topicid = $(this).attr('value');
var button_follow_html = $(this).html();
if ($(this).is("a[disabled]")){ return false; }
$("#follow-topic button").html('<?php echo $_LANGS['system']['loading_button']; ?>');
$(this).attr({ disabled: true});
$.ajax({
url: "",
data: { follow_topic: topicid },
type: "POST",
success: function (data) {
$("#follow-topic").html(data);
$("#follow-topic").attr({ disabled: false});
},
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
});
});
我已将按钮值更改为 $_LANGS['system']['loading_button']
但我想返回$_LANGS['forum']['follow']
如果ajax失败或者客户端失去连接。
这个系统使用多种语言,如果ajax成功,按钮将被替换为跟随按钮,所以我不能使用$("#follow-topic button").html('<?php echo $_LANGS['forum']['follow']; ?>');
.
抱歉我的英语不好,谢谢
最佳答案
来自jQuery documentation ,如果 ajax 调用失败则调用的 error
函数需要 3 个参数:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
因此,您实际上是在这段代码的 button_follow_html
变量中得到了 textStatus
响应:
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
参数是可选的,因此您可以这样做:
error: function(data) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
button_follow_html
不会被重新定义,并且仍然具有与 ajax 调用之前相同的值,因此您可以按原样使用它。
关于javascript - Jquery 将参数添加到 $.ajax 上的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31093784/