javascript - PHP XmlHttpRequest 错误与简单的待办事项列表

标签 javascript php ajax xmlhttprequest

作为 PHP 和 ajax XmlHttpRequest 调用的新手,我正在努力找出我的代码出了什么问题。浏览了文档,但我似乎正在努力将数据库行名称放入数组中。理想情况下,我希望在输入下方异步显示一个 innerHTML 来指示该项目是否在数据库中。现在它显示“未定义”,如下所示,直到我在数据库中输入最后一项。它仅响应数据库中的最后一项,这意味着我的循环可能存在问题。欢迎任何帮助。

enter image description here

enter image description here

index.php

<?php 
include 'db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">

    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous">
    </script>

    <script src="js/todo.js" type="text/javascript"></script>

    <script>

    </script>


</head>
<body onload="process()">
    <div class="list">
        <h1 class="header">My To Do</h1>
        <form>
            <ul class="items">
            <?php 
                $sql = "SELECT * FROM items ORDER BY items.id ASC";
                $result = mysqli_query($conn, $sql);

                if(mysqli_num_rows($result) > 0){
                    while ($row = mysqli_fetch_assoc($result)){
                        echo "<li><input type='checkbox' /><label>";
                        echo $row['name'];
                        echo "</label></li><br>";
                    }
                } else {
                    echo "There are no to-dos!";
                }

                echo "<br/><br/>";
                echo "<li><input type='checkbox' /><label>Mark all as completed</label></li>";
            ?>
            </ul><br />
        </form>
    </div>

    <div class="list">
        <form class="item-add" method="post">
            <input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off" required>
            <input name="myBtn" type="submit" value="Add Item">
            <div id="status"></div>
        </form>
    </div>

</body>

item.php

<?php
include 'db.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
    if (mysqli_connect_errno()) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
    }

    $sql = "SELECT * FROM items ORDER BY items.id ASC";
    $result = mysqli_query($conn, $sql);
    $itemArray = array();

    $rowNum = mysqli_num_rows($result);

    //is this the correct way to add db items to an array?
    if($rowNum > 0){
        while ($row = mysqli_fetch_assoc($result)){
            for ($x = 0; $x <= $rowNum; $x++) {

                $itemArray[$x] = $row['name'];  
            }

        }

    } else {
        echo "There are no to-dos!";
    }

    $entry   = $_GET['name'];
    if(in_array($entry, $itemArray))
        echo 'Item ' .$entry. ' already exists! Please enter a new item...';
    elseif ($name == '') 
        echo "Please enter an item...";
    else {
        //code for insertion
            echo "Successfully Inserted";

    }

echo '</response>';

?>

item.js

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
    var xmlHttp;

    if(window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            xmlHttp = false;
        }
    } else {
        try {
            xmlHttp = new XMLHttpRequest();
        } catch(e) {
            xmlHttp = false;
        }
    }

    if(!xmlHttp) {
        alert("cant create that object hoss");
    } else {
        return xmlHttp;
    }

}

function process() {
    if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
        name = encodeURIComponent(document.getElementById('name').value);
        xmlHttp.open("GET", "item.php?name="+name, true);
        xmlHttp.onreadystatechange = handleServerResponse;

        xmlHttp.send(null);
    } else {
        setTimeout('process()', 1000);
    }
}

function handleServerResponse(){
    if(xmlHttp.readyState==4) {
        if(xmlHttp.status==200){
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            console.log(xmlResponse.documentElement);
            message = xmlDocumentElement.firstChild.data;
            document.getElementById('status').innerHTML = 
            '<span style="color:blue">' + message + '</span>';
            setTimeout('process()', 1000);
        } else {
            alert('Something went wrong!');
        }
    }

}

最佳答案

$name 未在您的 PHP 文件中定义,您检查下面的 elseif 条件是否应该是 $entry

$entry   = $_GET['name'];
if(in_array($entry, $itemArray))
    echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($entry == '') 
    echo "Please enter an item...";
else {
    //code for insertion
        echo "Successfully Inserted";

}

将数据库列分配给数组的正确方法应该如下所示。

if($rowNum > 0){
        while ($row = mysqli_fetch_assoc($result)){

                $itemArray[] = $row['name'];  
        }

    } else {
        echo "There are no to-dos!";
    }

关于javascript - PHP XmlHttpRequest 错误与简单的待办事项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240056/

相关文章:

javascript - onclick 类不会触发动态数据

javascript - 从 JavaScript 的下拉列表中获取多个值

javascript - 神秘的 'function' 被附加到阵列

javascript - Material 组件 : Keeping Menu "Open" when clicking inside

php - Laravel Breeze - Tailwind CSS 未在登录和注册页面上加载

javascript - Ajax 调用检查复选框

javascript - 拦截React点击事件

php - 在 PHP 中以大写字母拆分?

php - 移除删除复选框 Sonata Admin Bundle

java - 成功提交表单数据后如何重定向用户?