代码之家  ›  专栏  ›  技术社区  ›  Vijunav Vastivch

成功后获取ajax变量参数

  •  0
  • Vijunav Vastivch  · 技术社区  · 6 年前

    这是我的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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Tetsuya Yamamoto    6 年前

    问题是 currentUrl 定义为此行中的客户端变量:

    var currentUrl = window.location.href;
    

    注意 @Url.Action() 帮助程序是在服务器端执行的,您不能使用 当前URL 客户端变量在其内部作为动作参数(它不存在服务器端变量)。您需要使用这样的查询字符串重定向到 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 })';