jquery - 使用ajax调用后从控制器返回的数据
问题描述
我有以下 Ajax 调用:
$.ajax({
url: '@Url.Action("DeleteUser", "Tribes")',
dataType: "json",
type: "Post",
data: {
"tribeId": tribeId,
"buId": buId,
"userId": userId
},
success: function(data) {
if (data.status === "success") {
$.smallBox({
title: "<strong>User Deleted</strong>",
content: "<i class='fa fa-clock-o'></i> <i>Tribe user was successfully deleted! <strong></strong></i>",
color: "#659265",
iconSmall: "fa fa-check fa-2x fadeInRight animated",
timeout: 4000
},
function(data) {
window.location.href = '@Url.Action("ViewTribeUsers", "Tribes", new
{
tribeId = data.tribeId,
buId = data.buId
})';
});
}
}
});
我的控制器如下所示:
public ActionResult DeleteUser(int tribeId, int buId, string userId)
{
clsTribes.DeleteTribeUsers(tribeId, userId);
return Json(new
{
status = "success",
tribeId = tribeId,
buId = buId
}, JsonRequestBehavior.AllowGet);
}
如何data.[variables]
在 AJAX 调用之后使用?在这种情况下,我得到的错误是在这一行的 data.[variable] 上:
window.location.href = '@Url.Action("ViewTribeUsers", "Tribes", new
{
tribeId = data.tribeId,
buId = data.buId
})';
错误:当前上下文中不存在名称“数据”
我相信它一定很简单,任何帮助将不胜感激!
谢谢!
解决方案
问题是因为data
它是一个客户端 JS 变量,您不能在服务器端 C# 代码中使用它。
一种可能的解决方法是使用Url.Action
构建基本 URL,然后将属性附加data
到它,如下所示:
function (data) {
window.location.href = '@Url.Action("ViewTribeUsers", "Tribes")?tribeId=' + data.tribeId + '&buId=' + data.buId;
});
这样做的缺点是您不会获得路由此 URL 的好处。它也变得更难维护,因为如果您更改路由模式,您需要记住更新此 JS 逻辑。
推荐阅读
- excel - Excel条件格式输入后将填充颜色更改为正常
- r - R:不平衡面板,为独特的观察创建假人
- django - 如何通过多个 http 请求打开会话以保留登录凭据?
- postgresql - 如何从 Postgres 的列中删除不间断的空格
- sql - 使用带有动态参数的过程选择 INTO 动态临时表
- python - 是否有替代 `difflib.get_close_matches()` 的替代方法,它返回索引(列表位置)而不是 str 列表?
- python - 同一列联表的 sklearn 和 scipy.stats 中的不同 chi2 值
- php - 调用laravel关系时避免字符串
- python - 在 python 中加载 ddl 进入 Windows 错误 0xE0434F4D
- javascript - 使用 javascript 展平嵌套的 json 数组