使用post方法时,AJAX调用php不返​​回值

时间:2016-10-25 12:21:26

标签: javascript php ajax

PHP代码

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "ngram";

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $uid =$_REQUEST["username"];
    $sql = 'select * from user_db where username like '.'"'.$uid.'"';
    $result = $conn->query($sql);
    //echo $sql;
    if ($result->num_rows > 0) 
    {
        $conn->close();
        echo (0);
    }
    else 
    {   
        $conn->query("insert into user_db values('".$_REQUEST["name"]."','".$_REQUEST["username"]."','".$_REQUEST["email"]."','".$_REQUEST["pass"]."')");
        $conn->close();
        echo (1);
    } 

&GT;

function connectDb(formElement)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","signup.php",true);
    xmlhttp.onreadystatechange=function() 
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            myFunction(xmlhttp.responseText);
        }
    }
    xmlhttp.send(new FormData (formElement));
}
function myFunction(response)
{   
    if(response != 1)
    {
        window.open("error.html","_self");
    }
    else
    {
        window.open("login.html","_self");
    }
}

这里javascript能够发送请求,但php没有返回任何值。值将添加到数据库,但页面不会更改。只有返回的值会显示在屏幕上。

1 个答案:

答案 0 :(得分:1)

你写return $r但不写函数来访问它。写一个函数或者写echo $r;