Ajax POST 请求适用于本地主机,但不适用于网站

问题描述 投票:0回答:1

我正在开展一个可以搜索化合物的项目。

我的搜索栏有自动完成功能,但在托管网站时出现错误。这是我得到的错误:

未捕获的语法错误:JSON 输入意外结束 在 JSON.parse() 在 ajax_request.onreadystatechange

这是前端页面:

function autocomplete(inp) {
        /*the autocomplete function takes two arguments,
        the text field element and an array of possible autocompleted values:*/
        var currentFocus;

        /*execute a function when someone writes in the text field:*/
        inp.addEventListener("input", function(e) {
            var a, b, i, val = this.value;
            /*close any already open lists of autocompleted values*/
            closeAllLists();
            if (!val) {
                return false;
            }

            currentFocus = -1;
            /*create a DIV element that will contain the items (values):*/
            a = document.createElement("DIV");
            a.setAttribute("id", this.id + "autocomplete-list");
            a.setAttribute("class", "autocomplete-items");
            /*append the DIV element as a child of the autocomplete container:*/
            this.parentNode.appendChild(a);

            // Check if the user input is at least one character
            if (val.length >= 1) {
                // Create form data to submit with php

                var form_data = new FormData();

                form_data.append('query', val);

                // Create ajax request
                var ajax_request = new XMLHttpRequest();

                ajax_request.open('POST', 'process_data.php', true);
                ajax_request.send(form_data);


                ajax_request.onreadystatechange = function() {
                    if (ajax_request.readyState == 4 && ajax_request.status == 200) {

                        // Store the matching compounds in an array
                        var arr = JSON.parse(ajax_request.responseText);

                        console.log(arr);

                        /*for each item in the array...*/
                        for (i = 0; i < arr.length; i++) {
                            /*check if the item starts with the same letters as the text field value:*/

                            /*create a DIV element for each matching element:*/
                            b = document.createElement("DIV");
                            /*make the matching letters bold:*/
                            b.innerHTML = "<strong>" + arr[i].title.substr(0, val.length) + "</strong>";
                            b.innerHTML += arr[i].title.substr(val.length);
                            b.innerHTML += " - " + arr[i].name;
                            /*insert a input field that will hold the current array item's value:*/
                            b.innerHTML += "<input type='hidden' value='" + arr[i].title + "'>";
                            /*execute a function when someone clicks on the item value (DIV element):*/
                            b.addEventListener("click", function(e) {
                                /*insert the value for the autocomplete text field:*/
                                inp.value = this.getElementsByTagName("input")[0].value;
                                /*close the list of autocompleted values,
                                (or any other open lists of autocompleted values:*/
                                closeAllLists();
                            });
                            a.appendChild(b);

                        }

                    }
                }
            }
        });

这是后端代码(php)process_data.php:

<?php

include("path.php");
include(ROOT_PATH . '/app/database/mysqli.connect.php');
include(ROOT_PATH . '/app/database/db.php');


if (isset($_POST["query"])) { 

    $query = $_POST['query'];

    $result = selectALL("formulae", ['enabled' => 1]);

    $autocompleteResult = array();
    if ($result) {
        foreach ($result as $row) {
            //array_push($autocompleteResult, );
            $autocompleteResult[$row['id']]['title'] = strip_tags($row["title"]);
            $autocompleteResult[$row['id']]['name'] = $row["name"];
        }
    }

    $autocompleteResult = array_values($autocompleteResult);

    $listResult = array();

    for ($i = 0; $i < count($autocompleteResult); $i++) {
        if (strtoupper(substr($autocompleteResult[$i]['title'], 0, strlen($query))) == strtoupper($query) || strtoupper(substr($autocompleteResult[$i]['name'], 0, strlen($query))) == strtoupper($query)) {
            $listResult[$i]['title'] = $autocompleteResult[$i]["title"];
            $listResult[$i]['name'] = $autocompleteResult[$i]["name"];
        }
    }

    $listResult = array_values($listResult);

    echo json_encode($listResult);
}

感谢您提前帮助我!

我尝试更改 javascript 以查看是否有问题,以及过滤搜索的后端脚本

调试详情:

控制台

javascript php ajax
1个回答
-2
投票

在调用 JSON.parse() 之前尝试 console.log(ajax_request.responseText) 并查看它。

© www.soinside.com 2019 - 2024. All rights reserved.