javascript 通过 AJAX 调用的 PHP header() 无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9851792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:02:47  来源:igfitidea点击:

PHP header() called via AJAX not working properly

phpjavascriptmysqlajax

提问by badcoder

I'm new to web development.

我是网络开发的新手。

Right now I'm working on a login feature on a site. I used Javascript/AJAX to fetch the username and password and send it to a PHP file for verification on the MYSQL database. That's what I'm about to make.

现在我正在研究网站上的登录功能。我使用 Javascript/AJAX 获取用户名和密码并将其发送到 PHP 文件以在 MYSQL 数据库上进行验证。这就是我要做的。

My question is why can't the header() function working properly? I want after the user login she is redirected to the profile page (profile.php)

我的问题是为什么 header() 函数不能正常工作?我想在用户登录后将她重定向到个人资料页面 (profile.php)

Here's snippet of the PHP (login.php):

这是 PHP (login.php) 的片段:

$query = "SELECT * from user WHERE username = '$uname' AND password = md5('$pass');";
$ret = mysql_query($query) or die(mysql_error());

if(!$ret) {
    $msg = "Invalid query " . mysql_error() . "\n";
    $msg .= "Whole query " . $query;
    die($msg);
}

$userid = -1;
while($row = mysql_fetch_array($ret)) {
    $userid = $row["ID"];
}

$cnt = mysql_num_rows($ret);
if($cnt == 1) {
    session_start();
    $_SESSION["userid"] = $userid;
    $_SESSION["uname"] = $uname;
    echo "You have logged in successfully!";
    header("Location: profile.php");
} else {
    echo "Wrong Username/Password";
}

And here's for the Javascript (an AJAX function):

这是 Javascript(一个 AJAX 函数):

var obj;
    var url = "login.php";
    var params = "uname=" + document.getElementsByName("uname")[0].value + "&pass=" + document.getElementsByName("pass")[0].value;
    if(window.XMLHttpRequest) { // Major browsers
        obj = new XMLHttpRequest();
        obj.open("POST",url,true); 
        obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        obj.setRequestHeader("Content-length", params.length);
        obj.setRequestHeader("Connection", "close");
        obj.onreadystatechange = function() {
            if(obj.readyState == 4) {
                if(obj.status == 200) {
                    // success
                } else {
                    alert("Problem in returned data" + "Error status=" + obj.status);
                }
            }
        }
        obj.send(params);

回答by F21

I don't think the redirect will work with AJAX. This is what will happen:

我认为重定向不适用于 AJAX。这是会发生的事情:

  1. AJAX request is sent to login.php
  2. login.phpsends back a header with Location: profile.php
  3. The browser then redirects and fetches profile.php
  4. The results of profile.phpis then passed to your XMLHttpRequest Object.
  1. AJAX 请求被发送到 login.php
  2. login.php发回一个标头 Location: profile.php
  3. 然后浏览器重定向并获取 profile.php
  4. profile.php然后将结果传递给您的 XMLHttpRequest 对象。

A way to get the AJAX response to redirect your page is to do this:

获取 AJAX 响应以重定向页面的一种方法是执行以下操作:

  • The response from login.phpreturns a JSON response containing the status code (302 or 301) and the location to redirect to.

  • The response itself has a status code of 200 (successful).

  • The process the JSON response and check the status code for 302 or 301 and redirect to the location.

  • 来自的响应login.php返回一个 JSON 响应,其中包含状态代码(302 或 301)和要重定向到的位置。

  • 响应本身的状态代码为 200(成功)。

  • 处理 JSON 响应并检查 302 或 301 的状态代码并重定向到该位置。

回答by itsmequinn

You need to take out the echo statement before header(). Header won't work if anything has been output to the browser before it is called.

需要去掉header()前的echo语句。如果在调用之前向浏览器输出了任何内容,则标题将不起作用。

Here's the php docon that.

这是php 文档

回答by ncremins

What's happening exactly?

究竟发生了什么?

After header()is called in php, php still executes the rest of the script unless you stick an exit;after the header()call. This is only if you don't want to execute the rest of login.php

之后header()被称为在PHP,PHP,除非你坚持的仍执行脚本的休息exit;header()调用。这仅在您不想执行其余部分时login.php

回答by Rajesh Mahajan

You can one thing replace your code header("Location: profile.php");by echo "window.location.href='profile.php';and replace your success function as

你可以一件事取代你的代码header("Location: profile.php");通过echo "window.location.href='profile.php';并替换你的成功的功能

     if(obj.status == 200) {
         eval(obj.responseText);
     }

Thats it. now a response will be evaluated by script and will redirect your page on profile.php

而已。现在响应将由脚本评估,并将重定向到 profile.php 上的页面