未定义JSON错误请求
JSON error request is not defined
当我执行console.log(req.responsetext)时,我得到[11:38:04.967]ReferenceError: req未定义。但我定义的req作为一个新的xml请求在窗口加载,所以我有点难倒。有什么方法可以让我传递一个参考吗?
控制台输出如下
[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);
}
?>
范围问题!把req前面的var去掉,使它全局化,它就可以工作了
相关文章:
- 尝试发布大型JSON数据时出现错误请求错误
- 仅在 IE 中使用 jQuery 发布数据时出现错误请求错误
- JavaScript JSONP请求错误--未捕获的语法错误:意外的令牌:
- 正在生成$http.get请求..错误
- CORS预检请求错误无法通过安装npm cors软件包解决
- JSON PUT 请求错误
- 400 错误请求错误在 Ajax POST 到 spring RestController
- 使用 cURL 请求 svg.sencha.io 时请求错误
- WCF Web 服务在通过 Javascript 调用时返回“错误请求”错误
- JSFiddle “请使用后请求”错误
- 使用 JS 更改映像路径的请求错误
- AngularJS对跨源资源执行OPTIONS HTTP请求=>错误401
- 条纹::无效请求错误(此客户没有附加的付款来源)
- JSON 请求错误 500
- Ajax 请求错误 404
- 在 Node.js 服务器内发出异步请求错误:“类型错误:对象 #<对象> 没有方法'_implicitHeader'”
- 为什么这个 $.getJSON 请求错误
- 角度/业力 - 预期请求和观察到的请求相同时的“意外请求”错误
- 从 Mapbox.js 使用“LoadURL()”时出现“跨源请求错误”
- Chrome 应用/扩展程序 - 后台请求错误,或允许应用问题加载 Google 文档 API