获取成功参数后的Ajax变量
以下是我的Ajax代码:获取成功参数后的Ajax变量,ajax,asp.net-mvc,Ajax,Asp.net Mvc,以下是我的Ajax代码: $("#generateImage").click(function () { var url = $(this).data('url'); var currentUrl =window.location.href; $.ajax({ type: "post", contentType: "application/json; charset=utf-8",
$("#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 })';
当前URL显示:
在当前上下文中不存在
我的问题是:
如何使currentUrl在该特定位置有效
否则数据上就没有错误:零件?数据:{'urlVar':'+currentUrl问题是currentUrl定义为此行中的客户端变量:
var currentUrl = window.location.href;
请注意,@Url.Action helper是在服务器端执行的,您不能将其中的currentUrl客户端变量用作操作参数,因为它不作为服务器端变量存在。您需要使用如下查询字符串重定向到GetData操作方法:
if (response != null && response.success) {
alert("Success");
// use query string here
window.location = '@Url.Action("GetData", "MyController")?urlVar=' + currentUrl;
}
如果要从服务器端获取URL,请修改URL.Action helper以包含Request.URL、Request.RawUrl或Request.URL.AbsoluteUri:
更新:
对于多个参数,可以使用以下任一查询字符串参数:
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 })';
谢谢@TetsuyaYamamoto如果我使用变量呢?我的myheight和mywidth现在声明为静态的,如果我还需要变量中的值呢?这取决于您想如何为它们赋值。例如,如果您想将服务器端变量传递到客户端变量,只需使用如下声明:var mywidth=@width,然后使用“mywidth”:mywidth。如果我需要javascript中的mywidth和myheight的值,如何?可能吗?是的,可能。只需像我前面所说的那样以JSON字符串传递它们:数据:{'urlVar':'+currentUrl+','mywidth':'+mywidth+','myheight':'+myheight+},确保已经为您分配了myWidth和myHeight变量。是的,我找到了,但我的问题是我需要在这里放置宽度和高度@Url.Action,类似于new{urlVar=Request.Url.ToString,width=varwidthvalue,height=varheightvalue}
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString(), width = varwidthvalue, height = varheightvalue })';