首页 > 解决方案 > 成功参数后获取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

标签: ajaxasp.net-mvc

解决方案


该问题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.UrlRequest.RawUrlRequest.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;

或者如果两者varwidthvaluevarheightvalue都是服务器端变量,只需使用这个:

window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString(), width = varwidthvalue, height = varheightvalue })';

推荐阅读