jquery - 当值为真时需要重定向到页面
问题描述
当基于ajax调用的值为真时需要重定向到页面。问题是,如果返回 true 或 false,页面将被重定向。
<a class="btn btn-warning" onclick="return clickthis(25007); " href="test.aspx?id=eheAhgpAS38=">Start </a>
function clickthis(obj) {
var bValid = false;
function ajax1() {
return $.ajax({
type: "POST",
url: "order.aspx/ActivateLocation",
data: '{id:' + obj + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(r) {
if (r.d == "1") {
bValid = true;
} else {
$('#overlay').remove();
$.growl.error({
title: "Error",
message: "An error occurred, Please try again."
});
bValid = false;
}
}
});
}
$.when(ajax1()).done(function(a1) {
return bValid;
});
}
解决方案
首先,没有事件传递给clickthis()
函数,在这方面你似乎对不显眼的事件处理程序感到困惑。另请注意,当您尝试从done()
处理程序执行操作时,您无法从异步方法调用返回任何内容。window.location.assign()
相反,您可以只调用$.ajax()
回调。
<a class="btn btn-warning" data-id="25007" href="test.aspx?id=eheAhgpAS38=">Start </a>
$('a.btn').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "order.aspx/ActivateLocation",
data: { id: obj },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(r) {
$('#overlay').remove();
if (r.d == "1") {
window.location.assign($(this).attr('href'));
} else {
$.growl.error({
title: "Error",
message: "An error occurred, Please try again."
});
}
}
});
});
请注意,在上面的示例中,我向data
. 这是将字符串连接在一起的首选做法。
推荐阅读
- c++ - How to delete an entry in SQLite ORM with a composite key
- python - Printing of exception subclasses is not a tuple of arguments
- javascript - 不创建表
- javascript - Get info from a class and turn it to an array
- python - 如何插入累积直方图数据?
- php - Array of strings - translation
- python - 尝试将响应解析为 JSON 格式时收到 JSONDecodeError
- python - `try ... except not` 构造
- laravel - VideoJs 不在浏览器和设备上播放
- hive - Hive join 与消耗更多 timr 的大表