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>');
                }
            }
        });
    }
});

图片转代码服务由CSDN问答提供 功能建议

我有一个文件(confirm.js),如果用户名和密码,它会将登录页面重定向到主页 输入正确。 我收到错误:

 &lt;?php header(“Location:../ MedCompany / homepage.php?&gt; 
  <  / pre> 
 
 

我从控制台收到的错误如下:

Uncaught Syntaxerror:意外的令牌&lt;

我应该如何在我的javascript文档中包含php代码,以便它可以重定向到另一个php文件。为什么我的代码不正确?

我认为&lt; php?php code?&gt; 是这样做的正确方法

  $('document')。ready(function(function)  ){
 button = document.getElementById(“button”); 
 button.onclick = function(){
 var data = $(“#loginform”)。serialize(); 
 $ .ajax({\  n类型:'POST',
 url:'.. / MedCompany / php / welcome.php',
 data:data,
 success:function(response){
 console.log(“response was”+ 响应); 
 if(response ==“Login Succesfull”){
  &lt;?php 
 header(“Location:../ MedCompany / homepage.php”); 
?&gt; 
} 
 else {
 $(“#error”)。html('&lt; div  class =“alert alert-info”role =“alert”&gt ;;'+ response +'&lt; / div&gt;'); 
} 
} 
}); 
} 
}); 
    
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)

相关推荐 更多相似问题