XMLHttpRequest和PHP的问题

Problems with XMLHttpRequest and PHP

本文关键字:问题 PHP XMLHttpRequest      更新时间:2023-09-26

我对JavaScript和PHP都很陌生,所以我希望这个问题不像我看起来那么复杂。我正试图使用XMLHttpRequest将数据从表单发送到PHP文件,然后将PHP的输出显示为警报。这是HTML和JavaScript:

<form onSubmit="password_Check()"> 
        <input type="password" size="40" name="password" id="pass"> 
        <input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
    var url = "test.php";
    var pass = $("#pass").val();
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url+"?pass="+pass, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
        }
    }
}   
</script>

这是PHP:

<?php
    $pass = $_GET["pass"];
    echo "The password is $pass!  We've done it!";
?>

我已经尝试了各种方法来实现这一点,比如$.post、$.get、$.ajax和使用post的xhr。但我似乎无法让它发挥作用。现在,它只是在当前url的末尾附加"?password=(无论我放什么)",这并没有什么作用,但它表明它正在做一些事情。

在代码中,您缺少实际触发请求的send部分。若并没有触发请求,那个么侦听状态更改的事件侦听器就并没有意义。

像一样吗

xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
    alert(xhr.responseText);
    }
}
xhr.send();

在您的问题中,您还提到了jquery-ajax,使用$.get,您的代码可以像一样简单

$("#form1").on("submit",function(e){
    e.preventDefault();
    var url = "test.php?pass=" + $("#pass").val(); 
    $.get(url,function(data){
       //handle data here
    });
});

您忘记执行请求。xhr.send():

还要注意,由于您有一个XMLHTTPRequest,您需要使用.preventDefault(); 来防止默认行为(即要提交的表单)

<form id="form1"> 
        <input type="password" size="40" name="password" id="pass"> 
        <input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
    e.preventDefault(); // prevent from submitting
    var url = "test.php";
    var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
    var xhr = new XMLHttpRequest();
    var params = '?pass='+pass;
    xhr.open("GET", url+params, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
        }
    }
    xhr.send(); // send it
});
</script>

如果您正在使用jQuery,那么最好使用jQuery的ajax函数,而不是自己使用xhr!

此外,如果您正在提交密码,最好不要使用GET请求提交,因为它将在URL中可见。相反,在处理密码时始终使用POST!

客户端:

<form action="/index.php" id="myform" method="post">
        <input type="password" size="40" name="password" id="pass"> 
        <input type="submit" value="Go">
</form>
<script type="text/javascript">
  $('#myform').on('submit', function() {
      $.ajax({
        type: $(this).attr('method'), //Taking for the form attribute
        url: $(this).attr('action'),
        data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
        success: function(response) {
          if(response == 'success') {
            window.location.href = '/url-to-goto';  //Set your redirect url here
          }
          else {
            //Handle invalid password here
            alert(response);
          }
        }
      });
      return false;
  });
</script>

服务器端:

<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
  //Check password here
  if(isset($_POST['password']) && $_POST['password'] == '123') {
    die('success'); //successful! redirect user!
  }
  die('Invalid password!');
}
?>

希望这能帮助你更好地理解!