【问题标题】:How to use javascript to append the header of request before loading that page如何在加载该页面之前使用 javascript 附加请求的标头
【发布时间】:2018-12-08 05:09:06
【问题描述】:

我有 2 个 html 文件属于两个不同的控制器

这属于 SignupController 的 Index 动作

索引.html

<div class="signup-small-font pull-right"><a href="/Account/ResetPassword">Forgot password?</a></div>

当点击这个链接时,它会转到那个url并请求获取AccountController的ResetPassword Action的视图并获取resetPAssword.html

现在我想要的是在发出该请求之前,我需要在服务器端的请求中附加一个自定义标头。 我使用的是 ajax javascript:

function appendHeader(urlCulture){

$.ajax({
    type: 'GET',
    url: urlCulture,
    headers: {
        "Culture": 'zh'
    },

})
}

在请求 resetPassword.html 之前,我应该在 index.html 锚链接中调用这个函数吗

就像我想要的一样,当我点击它时,它将导航到 Account/Resetpassword 并使用从 javascript 文件中获取的响应来呈现而不是正常响应

【问题讨论】:

    标签: javascript .net ajax model-view-controller get


    【解决方案1】:

    你正在使用路由,你需要从javascript函数中获取url

    这里有一个例子: Get local href value from anchor (a) tag

    你可以做类似的东西:

    <div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>
    

    在你的 js 函数中,就像之前的回复一样,你可以做这样的事情:

    function appendCustomHeader(element){
    
        var url = element.href; // to get full url 
    
        $.ajax({
            type: 'GET',
            url: url, 
            headers: {
                "CustomHeader": 'YourCustomHeader'
            },
            success: function(res) {
                // here you make anything else with your response
            }
        })
    
       return false;
    }
    

    我没有测试过,希望对你有用。

    看来你可以禁用返回 false 的 href 重定向,

    看到这个:

    How can I disable HREF if onclick is executed?

    【讨论】:

    • 您好,这种方法还会发送两次请求,一次带有标头,一次没有标头
    • 然后“href”工作,即没有标头的请求。尝试使用不同的属性名称而不是“href”,我已经编辑了答案。请看。
    • 如果我更改为 route ,它不再导航到该页面。就像我想要的是当我点击它时,它将导航到 Account/Resetpassword 并使用从 javascript 文件中获取的响应来呈现而不是正常响应
    • 我已经编辑过了。返回 false 禁用 href 重定向,试试吧。
    • 设置 return false 不会导航到该页面,即使我仍然得到正确的响应。这不是我想要的。所以我的想法是我需要导航到该页面,但它会使用从 javascript 文件中获得的响应来呈现页面
    【解决方案2】:

    在你的 html 文件中

    <div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>
    

    在你的 js 中

    function appendHeader(urlCulture){
        $.ajax({
            type: 'GET',
            url: urlCulture,
            headers: {
                "Culture": 'zh'
            },
            success: function(res) {
                window.location = 'Account/ResetPassword';
            }
    
        })
    }
    

    试一试。我不太确定这是否是您想要做的。

    【讨论】:

    • 它说'window.location 不是一个函数'
    • 应该是window.location = "Account/ResetPassword";
    • 我已经更改到正确的位置,但现在的问题是 AccountController 被调用了两次,一次使用自定义标头,然后调用一次没有它
    • 你把href的值改成“#”了吗?
    • 是的,我已经这样做了,但似乎通过将 window.location 设置为 Account/ResetPassword 成功,使其再次触发帐户控制器中的操作
    猜你喜欢
    • 2023-03-24
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多