donglanche9257 2016-11-25 18:52
浏览 41
已采纳

包括将在javascript文件中重定向用户的Php代码?

I have a file (confirm.js) which will redirect a login page to a home page if the Username and Password were entered correctly. I am getting an error on the line:

<?php header("Location: ../MedCompany/homepage.php ?>

The error that I am receiving from the console is as following:

Uncaught Syntaxerror: Unexpected token <

How should I include the php code within my javascript document so it can redirect to another php file. Why is my code incorrect?

I thought <php? php code ?> is the proper way of doing this

$('document').ready(function () {
    button = document.getElementById("button");
    button.onclick = function () {
        var data = $("#loginform").serialize();
        $.ajax({
            type: 'POST',
            url: '../MedCompany/php/welcome.php',
            data: data,
            success: function (response) {
                console.log("response was " + response);
                if (response == "Login Succesfull") {
                    <?php
                    header("Location: ../MedCompany/homepage.php");
                    ?>
                }
                else {
                    $("#error").html('<div class="alert alert-info" role="alert">;' + response + '</div>');
                }
            }
        });
    }
});
  • 写回答

2条回答 默认 最新

  • drazvzi741287 2016-11-25 19:00
    关注

    You can't just plonk a bit of PHP in the middle of Javascript code and expect it to do what you want. The Javascript parser is attempting to parse it as Javascript and, funnily enough, isn't managing it.

    You need to redirect the browser using Javascript methods, i.e. setting the window.location object:

    window.location = "../MedCompany/homepage.php";
    

    Using the PHP method will only work when the PHP engine is working, i.e. when the code is being executed on the server, not in the browser.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型