【问题标题】:Why isn't the PHP file responding to my AJAX request?为什么 PHP 文件没有响应我的 AJAX 请求?
【发布时间】:2018-08-14 03:56:28
【问题描述】:

我有一个显示单词“PRESENT”的 HTML 文件。

当我点击单词时,我想向 PHP 文件发送 AJAX 请求,这会将屏幕和数据库中的单词更改为“ABSENT”。

有两个问题:

  1. PHP 从不响应 HTML 文件。如果是这样,changeState() 函数会触发“服务器已响应!”的警报

  2. 即使调用了 changeState() 函数,PHP 文件也不会执行 SQL 语句。如果是这样,数据库就会被更新,但事实并非如此。

index.html

<html>

  <head>
    <title>Attendance System</title>
  </head>

  <body>

    <div id="1">
      <span onclick="changeState(this)">PRESENT</span>
    </div>

    <script>

    function changeState(elem) {

      var oldValue = elem.innerHTML;
      var newvalue;
      var itemID = elem.parentNode.getAttribute('id');

      if (oldValue == 'PRESENT') {
        newvalue = 'ABSENT';
      } else {
        newvalue = 'PRESENT';
      }

      alert("new value is " + newvalue + ", itemID is " + itemID);

      var xmlhttp;

      if(window.XMLHttprequest) {
        xmlhttp = new XMLHttpRequest();
      } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
          alert("Server has responded!");
          elem.innerHTML = xmlhttp.responseText;
        }
      }

      xmlhttp.open("GET", "updateState.php?newValue=" + newvalue + "&id=" + itemID, true);
      xmlhttp.send();
    }

    </script>

  </body>
</html>

updateState.php

<?php

// Login procedure code here...

// I tried to substitute this palce with fixed dummy values before and it successfully updated the database. But the code doesn't work when it is like this.
$value = $_GET['newValue'];
$id = $_GET['id'];

// Construct SQL query
$query = "UPDATE attendanceList SET attendOrNot = '$value' WHERE id = '$id'";

// Execute SQL query
mysqli_query($conn, $query) or die('Query execution failed! ' . mysqli_error($conn));

// Print result text
print $value

?>

【问题讨论】:

  • 你从来没有设置过$value ?
  • @IsThisJavascript,好像他正在这样做。
  • 您的查询容易受到 MySQL 注入的攻击。您应该查找 prepared statments 并尝试一下,您将受到保护,' 之类的内容不会破坏您的查询。
  • @lonut 哎呀我没注意到他将$_GET 设置为$value
  • 从您的控制台检查您的网络选项卡。确保updateState.php 的路径正确。另外,我不认为$id 是一个字符串。所以应该是$id 没有' '

标签: javascript php mysql sql ajax


【解决方案1】:

index.html 中有语法错误

 if(window.XMLHttprequest) {
    xmlhttp = new XMLHttpRequest();
 } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

“XMLHttprequest”应该拼写为“XMLHttpRequest”,大写R。

很抱歉让大家感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2020-11-06
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多