使用POST和Javascript重定向到PHP脚本

时间:2017-04-04 18:17:59

标签: javascript php jquery ajax authentication

我已经找到了很多这个问题的答案,但它们似乎都不符合我的需要。

我正在通过Javascript处理用户身份验证,我需要传递的访问令牌是通过Javascript SDK获取的。我想要做的是通过POST方法将访问令牌传递给HTML / PHP页面,以便令牌不会在URL中公开。这需要在javascript回调中进行,这样我才能在成功进行身份验证时重定向用户。

我看到的所有建议都建议手动设置一个href变量,其中包含我在URL中声明的数据传递,但我不能使用此解决方案,因为这会暴露我的数据。

如何通过JS获取令牌,将其发布到PHP脚本,并显示与该脚本相关联的页面而不将令牌暴露给用户?

以下是我仅使用用户名作为示例的尝试:

$.ajax({
        data: 'username=' + username,
        url: 'confirmation.php',
        method: 'POST',
        success: function(msg) {
            //Not sure what to do here
        }
});

2 个答案:

答案 0 :(得分:0)

我认为你的ajax代码不正确。你可能想尝试这样的事情:

    $.ajax({type : "POST",
        url : "confirmation.php",
        data : { username :  username},
        success : function(result){
           window.location.replace("your_redirected_site_here");
        },
        error: function (xhr, status, error) {
            alert("-- ERROR IN AJAX --\n\n" + xhr.responseText);
        }
    });

当然,这只会检查ajax代码是否有效并且有一些已经发回的东西。我不建议像这样使用它。为什么不使用带有隐藏字段的表单,只有在必须发送后才填写?然后你的控制器(希望你使用MVC)可以处理身份验证,如果成功重定向到新页面。

javascript代码的示例

    <script>
    var authenticationToken; //you can still fill this with your own code

    $(document).ready(function() {
        $('#hiddenField').val(authenticationToken);
        myform.submit();
});
</script>

<form name="myform" action="yourControllerPage.php" method="POST">
    <input type="hidden" value="" id="hiddenField"/>
</form>

注意我使用Jquery!

答案 1 :(得分:-1)

将访问令牌放在请求的标头中

var accessToken = getAccessToken();
$.ajax({
    data: 'username=' + username,
    url: 'confirmation.php',
    headers: {
        "Authorization": "Bearer " + accessToken, 
        contentType: "application/json"
    },
    method: 'POST',
    success: function(msg) {
        //Not sure what to do here
        window.location.href = "/the/url/you/want/to/send/them/to.html";
    }

});