尝试在循环中解析请求长度时出现JSON错误

时间:2013-05-07 18:32:23

标签: javascript json

因此,我尝试制作一个简单的自动填充表单,但在尝试测试程序时不断出现错误。 当我尝试测试程序时,我的控制台吐出[11:25:26.267]语法错误:JSON.parse:意外字符@ /search.php:22就是这一行。我很确定我的语法很好,但我可能会弄错。任何和所有的帮助将非常感激。感谢任何花时间阅读和/或回答的人,即使你无法帮助!

for (var i = 0; i < response.length; i++)

我的完整代码如下。

编辑:现在有回声json的页面。当我执行console.log(req.responsetext)时,我得到[11:38:04.967] ReferenceError:未定义req。但我将req定义为窗口加载的新xml请求,所以我有点难过。

    <!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>Auto Complete</title>
</head>

<body>
    <script>
        window.onload = function () {
            var req = new XMLHttpRequest();     //the HTTP request which will invoke the query
            var input = document.getElementById('search');      //where to grab the search from
            var output = document.getElementById('results');    //where to display the sugestions

            input.oninput = getSuggestions;

            function getSuggestions() {
                req.onreadystatechange = function () {
                    output.innerHTML = "";  //CLEAR the previous results!! only once the server can process new ones though
                    if (this.readyState == 4 && input.value != "") {
                        var response = JSON.parse('(' + req.responseText + ')');
                        for (var i = 0; i < response.length; i++)
                            addSuggestion(response[i].terms);
                    }
                }               
                req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
                req.send(null);
            }

            addSuggestion = function (suggestion) {
                var div = document.createElement('div');
                var p = document.createElement('p');
                div.classList.add('suggestion');        //suggestion[x]...
                p.textContent = suggestion;             
                div.appendChild(p);
                output.appendChild(div);

                div.onclick = function() {
                    input.value = p.innerHTML;  //set the search box
                    getSuggestions();           //GET new suggesions
                }


            }
        }
    </script>

    <input type='text' id='search' name='search' autofocus='autofocus'>
    <div id='results'></div>
</body>
</html>

编辑这是我回复json的php页面。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

if (!isset($_GET['query']) || empty($_GET['query']))
    header('HTTP/1.0 400 Bad Request', true, 400);
else {


    $db = new PDO(
    my database
    );


    $search_query = $db->prepare("
        SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
    ");

    $params = array(
        ':keywords' => $_GET['query'] . '%',
    );

    $search_query->execute($params);
    $results = $search_query->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($results);
}
?>

1 个答案:

答案 0 :(得分:1)

摆脱JSON.parse中的(和)!

JSON.parse('(' + req.responseText + ')')

应该是

JSON.parse( req.responseText );

希望responseText是有效的JSON