PHP,使用AJAX将数据从javascript发送到PHP

时间:2017-02-09 20:00:54

标签: javascript php ajax

还没有解决这个问题。有人可以用我新的更新代码帮助我。新代码位于这篇文章的底部。

我正在学习PHP,现在我正在尝试学习使用AJAX将数据从JS传递到PHP。

这是我的表格:

<form id="login">
            <label><b>Username</b></label>
            <input type="text" name="username" id="username"
                   required>
            <label><b>Password</b></label>
            <input type="password" name="password" id="password"
                   required>
            <button type="button" id="submitLogin">Login</button>
        </form>

首先我有一个功能,如下所示:

try {
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    }else{
      Do stuff }
    }
 catch(error){ alert('"XMLHttpRequest failed!' + error.message); }

在此之后,我尝试使用新的FormData()将表单数据发送到php文件,但我不确定如何执行此操作。现在我有一个像这样的代码:

if (getElementById('username').value != "" & getElementById('password').value != "") {
    request.addEventListener('readystatechange', Login, false);
    request.open('GET', 'login.php', true);
    request.send(new FormData(getElementById('login')));
}

登录功能是一个测试功能

if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {

在我的PHP文件中,我现在有一个看起来像这样的函数:

session_start();
$logins = array('username1' => 'password1','username2' => 'password2');

if(isset($_GET['login'])) {
$Username = isset($_GET['username']) ? $_GET['username'] : '';
$Password = isset($_GET['password']) ? $_GET['password'] : '';

if (isset($logins[$Username]) && $logins[$Username] == $Password){
do stuff
}

我还需要将表单数据从js文件传递到php文件,以便检查输入数据是否与数组中的数据相同?

----------------------------------------------- ------------------------

新代码:

function LoginToSite() {
if (getElementById('username').value != "" && getElementById('password').value != "") {
    request.addEventListener('readystatechange', Login, false);

    var username = encodeURIComponent(document.getElementById("username").value);
    var password = encodeURIComponent(document.getElementById("password").value);


    request.open('GET', 'login.php?username='+username+"&password="+password, true);
    request.send(null);
}

}

function Login() {
if (request.readyState === 4 && request.status === 200) {
    alert("READY");
    var myResponse = JSON.parse(this.responseText);
    getElementById("count").innerHTML = myResponse;
    getElementById('login').style.display = "none";
    if(request.responseText == 1){
        alert("Login is successfull");
    }
    else if(request.responseText == 0){
        alert("Invalid Username or Password");
    }
}
else{
    alert("Error :Something went wrong");
}
request.send();

}

session_start();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
 if($username != '' and $password != ''){

foreach($user_array as $key=>$value){
    if(($key == $username) && ($value == $password)){
        echo "1";
    }else{
        echo "0";
    }
}

}else{
echo "0";
}

当我尝试登录时,网站首先警告某些内容出错,然后同样的事情再次发生,之后,它会提醒“准备就绪”。为了做到这一点,我需要改变什么?

2 个答案:

答案 0 :(得分:2)

尝试运行以下代码。

HTML:

<form id="login">
        <label><b>Username</b></label>
        <input type="text" name="username" id="username"
               required>
        <label><b>Password</b></label>
        <input type="password" name="password" id="password"
               required>
        <button type="button" id="submitLogin">Login</button>
    </form> 

JavaScript的:

function submitLogin{
var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var http = new XMLHttpRequest();
    var url = "login.php";
    var params = "username="+username+"&password="+password;
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            if(http.responseText == 1){
            alert("Login is successfull");
            }
            else{
            alert("Invalid Username or Password");
            }
        }
        else{
        alert("Error :Something went wrong");
        }
    }
    http.send(params);
}

PHP:

<?php
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_POST['username']) && isset($_POST['password'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
foreach($logins as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}

}else{
echo "0";
}

?>

我希望这会对你有所帮助。

答案 1 :(得分:0)

基本上你需要这样的东西(JS方面)

 // create and open XMLHttpRequest
 var xhr = new XMLHttpRequest;
 xhr.open ('POST', 'login.php'); // don't use GET


 // 'onload' event to handle response
 xhr.addEventListener ('load', function () {
     if (this.responseText == 'success')
         alert ('successfully logged in.');
     else
         alert ('failed to log in.');
 }, false);


 // prepare and send FormData
 var fd = new FormData;
 fd.append ('username', document.getElementById("username").value);
 fd.append ('password', document.getElementById("password").value);
 xhr.send (fd);

PHP代码( login.php )可能如下所示。

 # users array
 $logins = array ( 'username1' => 'pwd1', 'username2' => 'pwd2' );

 # validate inputs
 $u = isset ($_POST['username']) ? $_POST['username'] : false;
 $p = isset ($_POST['password']) ? $_POST['password'] : false;

 # check login
 if ($u !== false && $p !== false && isset ($logins[$u]) && $logins[$u] == $p)
     echo "success";
 else
     echo "error";

当然,建议首先检查功能XMLHttpRequestFormData是否存在。

 if (window['XMLHttpRequest'] && window['FormData']) {

     /* place your Ajax code here */

 }