Ajax:Javascript无法显示来自Server Response

时间:2016-05-12 01:31:06

标签: javascript html ajax

我目前正在尝试使用ajax在网站中创建搜索机器。我希望结果显示在我的主页中:

<div id="searchResults"></div>  

我也希望每个结果都是这样的:

<div id='product_box'>
   <h2 style='color: blue'>Result 1</h2>
   <b style='text-decoration: underline'>Price:</b> <b style='color: red'> 500 Euros</b><br><br>
   <b style='text-decoration: underline'>Description:</b> <b style='font-style: italic'>mpla mpla mpla</b>      
</div>; 

此外,我尝试将服务器响应创建为ResponseText而不是ResponseXML。但是,我希望服务器在我的页面中传递另外两个值。出于这个原因,我创建了以下代码:

<?php
/*---Interaction with the database---*/
$response = '<?xml version="1.0" encoding="UTF-8"?>';
$response .= '<response>';
$response .= '<numOfResults>' . $numOfProducts . '</numOfResults>';
$response .= '<maxNumOfProducts>' . $maxNumOfProducts . '</maxNumOfProducts>';

str = "";

while ($productsOfTheSearch = mysqli_fetch_array($query_select_products))
{
    $product_id = $productsOfTheSearch['product_id'];
    $product_title = $productsOfTheSearch['product_title'];
    $product_price = $productsOfTheSearch['product_price'];
    $product_desc = $productsOfTheSearch['product_desc'];

    $str .= "
        <div id='product_box'>
   <h2 style='color: blue'>$product_title</h2>
   <b style='text-decoration: underline'>Price:</b> <b style='color: red'> $product_price Euros</b><br><br>
   <b style='text-decoration: underline'>Description:</b> <b style='font-style: italic'>$product_desc</b>       
        </div>; 
        ";
}

$response .= '<results>' . $str . '</results>';

$response .= '</response>'; 
$response .= '</xml>';  

echo $response;

?>

我各自的js文件:

//Preparation functions... xmlHttp is the object from the XMLHttpRequest().
function handleServerResponse()
{
   if(xmlHttp.readyState==4 && xmlHttp.status==200)
   {
        response = (new DOMParser()).parseFromString(xmlHttp.responseText,'text/xml');

        x = response.getElementsByTagName("numOfResults");
        numOfResults = x[0].firstChild.data;
        x = response.getElementsByTagName("maxNumOfProducts");
        maxNumOfProducts = x[0].firstChild.data;

        //things with numOfResults and maxNumOfProducts.
        //These work fine!!!

        x = response.getElementsByTagName("results");

        document.getElementById("searchResults").innerHTML = x[0].firstChild.data

        setTimeout('searchFunction()', 200);

   }
}

tags -results中的文本通常在我的页面中传递,但无法显示。相反,它似乎是“未定义”这个词。

有人可以帮我解决这个问题吗? Perphaps,有没有更简单的方法来实现我的目标?

感谢先进的时间!!

0 个答案:

没有答案