我有一个我自己无法解决的问题。我用ajax做了一个搜索输入,在输入时提示结果。该脚本适用于Firefox,但是当我在chrome上使用它时,输入字段在输入时会失去焦点。
以下是代码:
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Please update your Browser");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = encodeURI(document.getElementById('campo-search-
modal
').value);
searchReq.open("GET", 'https://mywebsite.com/search.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('cont-list-re-search')
ss.innerHTML = '';
if (document.getElementById('campo-search-modal').value.length > 2) {
var str = searchReq.responseText.split("\n");
for (i = 0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<li ';
suggest += 'class="suggest_link">' + str[i] + '</li>';
ss.innerHTML += suggest;
}
}
else {
ss.innerHTML = 'Perfavore inserire almeno 3 caratteri!';
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('campo-search-modal').value = value;
document.getElementById('cont-list-re-search').innerHTML = '';
}
HTML代码:
<form>
<div class="form-group row row-camp-search">
<div class="col-5">
<input class="form-control modal-search" type="search" id="campo-search-
modal" placeholder="Ricerca Nel Sito..." onKeyUp="searchSuggest();">
</div>
</div>
</form>
<div id="result-search">
<ul id="cont-list-re-search">
</ul>
输入中的使用类型和ajax调用。我没有包含php搜索页面,因为只有查询数据库和圆圈才能打印结果。
奇怪的是,此脚本适用于Firefox,但在Google Chrome上使用时,输入字段会失去焦点。即使在第一封信之后。
PHP:
$search = $_GET["search"];
if(!empty($search))
{
try {
$connes = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME", $DB_USER,
$DB_PASS);
$connes->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmtb = $connes->prepare("SELECT * FROM table WHERE col like('%" .
simple_protect($search) . "%') ORDER BY col LIMIT 2");
$stmtb->execute();
$resulta = $stmtb->fetchAll();
}
catch(PDOException $b) {
echo "Error: " . $b->getMessage();
}
$connes = null;
if($resulta && count($resulta) > 0)
{
foreach($resulta as $key => $row)
{
echo '<a href="https://website.com/scheda/index.php?
dettagli='.strip_all($row['nome']).'"><div class="img-res-search"
style="background-image:url(https://website.com/img/miniature/min-
'.strip_all($row['icona']).')"></div><div class="tit-res-
search">'.strip_all($row['nome']).'</div></a><div class="dett-res-search">
<div class="dett1-res-search"><i class="fa fa-star" aria-hidden="true">
</i>'.strip_all($row['voto']).'</div><div class="dett2-res-search">
<i class="fa fa-flag" aria-hidden="true"></i>Section</div></div>'."\n";
}}
}
else
{
echo "Nessun Risultato!";
}
答案 0 :(得分:0)
我做了一个快速测试,尝试使用原始代码模拟问题,但我无法复制您在Chrome中提到的问题 - 在更正语法错误后,它在Chrome和Firefox中运行良好(可能只是因为复制) /粘贴此处)除了检查字段值字符串长度。字符串长度的测试应该在你进行ajax调用之前(如注释中所述)而不是在回调函数中。
问题:
encodeURI(document.getElementById('campo-search-
modal
').value);
在这样的多行上使用ID会产生令人讨厌的小错误。
然后我最终快速重写如下,其中一些可能是有意义的。
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>ajax search suggestions</title>
<script>
document.addEventListener('DOMContentLoaded',function(){
/* ultra basic ajax function */
function ajax( url, callback ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
};
xhr.open( 'GET', url, true );
xhr.send( null );
}
/* onkeyup event handler */
function searchSuggest( event ) {
var ss = document.getElementById('cont-list-re-search');
var callback=function(r){
ss.innerHTML = '';
var str = r.split("\n");
for( var i = 0; i < str.length - 1; i++ ) {
/* use DOM methods rather than string concatenation */
var li=document.createElement('li');
li.className='suggest_link';
li.innerHTML=str[i];
ss.appendChild( li );
}
/* bring focus back to form field */
this.focus();
};
/* Check length of input data BEFORE sending ajax request */
if( event.target.value.length > 2 ){
ajax.call( this, 'search.php?search='+event.target.value, callback.bind( event.target ) );
} else {
ss.innerHTML = 'Perfavore inserire almeno 3 caratteri!';
}
}
/* assign event handler */
document.getElementById('campo-search-modal').onkeyup=searchSuggest;
}, false );
</script>
</head>
<body>
<form>
<div class='form-group row row-camp-search'>
<div class='col-5'>
<input class='form-control modal-search' type='text' id='campo-search-modal' placeholder='Ricerca Nel Sito...' /><!-- removed inline event handler -->
</div>
</div>
</form>
<div id='result-search'>
<ul id='cont-list-re-search'></ul>
</body>
</html>
答案 1 :(得分:0)
是的,这在Chrome上占优势,特别是在Windows上。在其他机器上工作正常。
您可以通过从Bootstrap模式中删除“ tab-index = -1 ”来轻松解决此问题。这将解决您失去对ajax调用的关注的问题。
一个缺点是,Esc将无法继续失去焦点和模态关闭。