Ajax - живой поиск (проблемы с кодом)

336
26 ноября 2016, 17:57

Делал урок по Ajax поиску, когда вбиваю слово,оно должно проверяться через array в php файле и показывать есть ли оно или нет в array, но в результате почему то не работает. Подскажите пожалуйста в чём ошибка.

index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
    <h3>The chuf bla bla bla</h3>
    Enter food :
    <input type="text" id="userInput" />
    <div id="underInput" />
</body>
</html>

foodstore.php

<?php 
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
    $food = $_GET['food'];
    $foodArray = array('tuna','bacon','beef','ham');
    if(in_array($food, $foodArray))
        echo 'We have '.$food.'!';
    elseif ($food=='') 
        echo 'Enter food idiot';
    else
        echo 'We do not have '.$food.'!';
echo '</response>';
 ?>

foodstore.js

var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
    var xmlHttp;
    if(window.ActiveXObject){
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
            xmlHttp = false;
        }
    }else{
        try{
            xmlHttp = new XMLHttpRequest();
        }catch(e){
            xmlHttp = false;
        }
    }

    if (!xmlHttp) 
        alert("cant creATE that obj");
    else
        return xmlHttp;
}

function process(){
    if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
        food = encodeURIComponent(document.getElementById("useInput").value);
        xmlHttp.open("GET","foodstore.php?food=" + food, true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send(null);
    }else{
        setTimeout('process()',1000);
    }
}
function handleServerResponse(){
    if(xmlHttp.readyState==4){
        if(xmlHttp.status==200) {
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById("underInput").innerHTML = '<span style="color:blue">' + message + '</span>';
            setTimeout('process()',1000);
        }else{
            alert('Something went wrong!');
        }
    }
}
Answer 1

В php-коде ошибок нет (хотя рекомендую почитать про json и использовать его вместо xml). А так же если после приведенного кода в foodstore.php делаются какие-нибудь операции, после echo '</response>'; можете написать exit();.

Очень плохая практика отправлять каждую секунду запрос на сервер, если это не нужно. Нужно отправлять запрос (получать данные) только после изменения значения input, т.е. правильнее было бы повесить обрабочик на изменение значения:

var input = document.getElementById('userInput');
input.addEventListener('keyup', function() {
    alert('input changed to: ', input.value);
    // только после изменения вызываем process
    process(input.value);
});

Функцию createXmlHttpRequestObject (если вам не нужна поддержка старых IE, < IE7) можно удалить и сделать так:

var xmlHttp = new XMLHttpRequest();

Функции handleServerResponse и process верны за исключением вызова process каждую секунду: setTimeout('process()',1000);. У body onload="process()" тоже нужно удалить.

HTML:

<div>Enter food : <input type="text" id="userInput" /></div>
<div id="underInput"></div>

JS:

var input = document.getElementById('userInput');
input.addEventListener('keyup', function() {
    // alert('input changed to: ', input.value);
    process(input.value);
});
var xmlHttp = new XMLHttpRequest();
function process(inputValue) {
    var food = encodeURIComponent(inputValue);
    xmlHttp.open('GET', 'foodstore.php?food=' + food, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
}
function handleServerResponse() {
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
        xmlResponse = xmlHttp.responseXML;
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        document.getElementById('underInput').innerHTML = '<span style="color:blue">' + message + '</span>';
    } else{
        alert('Something went wrong!');
    }
}

Также всегда можно посмотреть, что возвращает сервер (в Chrome - открыть панель для разработчика (Ctrl+Shift+I), перейти на вкладку Network).

И да, не читайте статьи с ресурса, где вы нашли этот урок, они очень устаревшие.

READ ALSO
Получить иконку с openweathermap

Получить иконку с openweathermap

Есть запрос погоды на сайт openweathermapВ JSON ответе есть в поле weather

210
Перерисовать svg на канве

Перерисовать svg на канве

Здравствуйте! Возникла задача - нарисовать и скачать svg, вот такой структуры

238
Мягкий scroll помогите реализовать

Мягкий scroll помогите реализовать

Помогите реализовать мягкий скрол

329
Как засунуть в html переменную из node express?

Как засунуть в html переменную из node express?

Например сервер выдает ответ, красивой страницей html, в которой есть поле в котором нужно вывести сам ответ, ответ хранится в переменной node(например...

293