2013-05-07 80 views
1

當我做console.log(req.responsetext)我得到[11:38:04.967] ReferenceError:req沒有定義。但我將req定義爲一個新的窗口加載xml請求,所以我有點難住。有沒有辦法讓我通過參考?JSON錯誤請求未定義

控制檯輸出如下

[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms] 
[12:29:06.888] SyntaxError: JSON.parse: unexpected character @ search.php:21 
[12:33:24.316] console.log(req.responsetext) 
[12:33:24.318] ReferenceError: req is not defined 

任何和所有幫助將是非常感激地讚賞。謝謝任何花時間閱讀和/或回答的人,即使你無法幫助!

<!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> 

編輯這是我的PHP頁面,回聲的JSON。

<?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); 
} 
?> 
+0

你在哪裏實際調用'console.log(req.responseText)'? – Ian 2013-05-07 19:37:41

+0

在我的控制檯,當我用螢火蟲調試 – Chris 2013-05-07 19:38:06

+1

爲什麼你期望'req'被定義?你可以在'window.onload'的**裏面定義它**,這就是它的定義範圍。它沒有在全局範圍中定義(控制檯執行的地方) – Ian 2013-05-07 19:38:49

回答

0

範圍問題!刪除請求前的var使其成爲全局的,它應該工作

+0

這不是答案,但你確實幫我找到了,所以我非常感激! – Chris 2013-05-07 20:35:07