从阵列AJAX自动完成 [英] ajax autocomplete from array
问题描述
我想要创建一个简单的自动完成的文本框,从一个array.the code我使用(基于的这)是:
i'm trying to create a simple autocomplete textbox that takes the suggestions from an array.the code i'm using(based on this) is :
call.php
<?php
$list = array(
"Autocomplete",
"Metapher",
"Metatag");
for($i=0; $i<count($list); $i++){
if(strpos($list[$i], $_GET['str']) !== FALSE && strlen($_GET['str']) >= 2){
echo str_ireplace($_GET['str'], '<b style="color: red;">'.$_GET['str'].'</b>', $list[$i]) . '<br>';
}
}
?>
的index.php
index.php
<!DOCTYPE html>
<html>
<head>
<title>AJAX - 03</title>
<script type="text/javascript">
var ajax = new XMLHttpRequest;
function t(){
ajax.open("GET", "call.php?str=" + document.getElementById("test").value, false);
ajax.send();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("container").innerHTML = ajax.responseText;
}
}
}
</script>
</head>
<body>
<div id="container" style="border: 3px; border-style: solid; font-size: 42pt; border-radius: 7px;">
Text
</div>
<br><br>
<input id="test" type="text" onkeyup="javascript:t()">
</body>
</html>
但没有出现在建议box.I找不到任何语法错误,所以我想有一些错误的逻辑?
but nothing comes up at the suggestion box.I can't find any syntax errors so i suppose there is something wrong with the logic?
更新: 从PLB和FAngel的意见后,我加入的onreadystatechange和checks.However它仍然没有按;吨工作properly.Actually我只是发现,如果你键入的字母都在里面的3个字的建议,拿出正确的一个compination。它只是不工作,如果你输入一个word.For例子的起始字母,如果我给COM作为输入单词自动完成来up.However如果我给引渡,然后nothing.So我猜的实际问题是在这里:
UPDATE: after the advice from PLB and FAngel i added the onreadystatechange and the checks.However it still doesn;t work properly.Actually i just found that if you type a compination of letters that are inside one of the 3 words the suggestions come up properly.It just doesnt work if you type the starting letters of a word.For example if i give "com" as input the word Autocomplete comes up.However if i give "Aut" then nothing.So i guess the actual problem is here:
if(**strpos($list[$i], $_GET['str']) !== FALSE** && strlen($_GET['str']) >= 2)
从我读到这里 http://php.net/manual/en/function .strpos.php 问题可能是使用!=我却用!==我should.Any想法?
From what i read here http://php.net/manual/en/function.strpos.php the problem could be the use of != but i use !== as i should.Any thoughts?
推荐答案
你缺少你的要求是异步的。所以,当你运行该行:的document.getElementById(容器)的innerHTML = ajax.responseText;
,请求尚未完成。看看这个。 的onreadystatechange
是你所需要的。或者打这通电话同步
You are missing that your request is asynchronous. So when you run this line: document.getElementById("container").innerHTML = ajax.responseText;
, request is not done yet. Take a look at this . onreadystatechange
is what you need. Or make that call synchronous
这篇关于从阵列AJAX自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!