ajax - 成功参数后获取Ajax变量
问题描述
这是我的 Ajax 代码:
$("#generateImage").click(function () {
var url = $(this).data('url');
var currentUrl =window.location.href;
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: url,
data: "{'urlVar':'"+ currentUrl +"','mywidth':'250','myheight':'480'}",
success: function (response) {
if (response != null && response.success) {
alert("Success");
window.location = '@Url.Action("GetData", "MyController", new { urlVar = currentUrl })';
} else {
alert("Failed");
}
},
});
在这部分代码中:
new { urlVar = currentUrl })';
currentUrl 说:
在当前上下文中不存在;
我的问题是:如何使currentUrl
在该特定位置有效?
否则部分没有错误data:
?data: "{'urlVar':'"+ currentUrl
解决方案
该问题currentUrl
在此行中定义为客户端变量:
var currentUrl = window.location.href;
请注意,@Url.Action()
助手是在服务器端执行的,您不能在currentUrl
其中使用客户端变量作为操作参数(它不作为服务器端变量存在)。您需要使用这样的查询字符串重定向到GetData
操作方法:
if (response != null && response.success) {
alert("Success");
// use query string here
window.location = '@Url.Action("GetData", "MyController")?urlVar=' + currentUrl;
}
如果您想从服务器端获取 URL,请修改您的帮助Url.Action
程序以包含或Request.Url
:Request.RawUrl
Request.Url.AbsoluteUri
// alternative 1
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.AbsoluteUri })';
// alternative 2
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString() })';
更新:
对于多个参数,您可以使用任一查询字符串参数:
window.location = '@Url.Action("GetData", "MyController")?urlVar=' + currentUrl + '&width=' + varwidthvalue + '&height=' + varheightvalue;
或者如果两者varwidthvalue
和varheightvalue
都是服务器端变量,只需使用这个:
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString(), width = varwidthvalue, height = varheightvalue })';
推荐阅读
- windows - Powershell 磁盘管理
- pdftron - PDFTRON 实例未在模型上第二次打开 pdf 文档
- c++ - DLL 中类外的模板定义(错误:不允许定义 dllimport 函数)
- bash - 将终端的输出重定向到 .csv 文件中的特定工作表
- javascript - React + Redux + Hook,状态更新出错
- php - 在 WordPress 的 do_shortcode() 中使用 PHP 变量
- matlab - “面积”和“周长”维度 - Matlab
- javascript - Angular 9 Google Maps API Place Autocomplete
- c# - 检查字符串是否包含 Visual Basic 列表中的任何字符串
- python - 使用循环时无法在 django 中加载静态图像