dougu9895 2015-11-05 18:18
浏览 64

将AJAX响应分成多个Div

I asked this question earlier but did not quite word it right. I am using a live search example with the following code:

<script>
    function showResult(str) {
        if (str.length==0) { 
            document.getElementById("livesearch").innerHTML="";
            document.getElementById("livesearch").style.border="0px";
            return;
        }
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else {  // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
                document.getElementById("livesearch").style.border="1px solid #A5ACB2";
            }
        }
        xmlhttp.open("GET","livesearch.php?q="+str,true);
        xmlhttp.send();
    }
</script>

This sets the contents of the livesearch Div to a list of items echoed by the php script livesearch.php. This is pretty close to my goal, but I actually want each echoed item to be in their own expandable div such as this JQuery example.

My return string looks like this:

Title 1
Info 1 about title 1
Info 2 about title 1
Title 2
Info 1 about title 2
Info 2 about title 2

Here is the livesearch.php:

<?php    
    $xmlDoc=new DOMDocument();
    $xmlDoc->load("spells.xml");

    $x=$xmlDoc->getElementsByTagName('title');
    $y=$xmlDoc->getElementsByTagName('type');
    $z=$xmlDoc->getElementsByTagName('casting');
    $a=$xmlDoc->getElementsByTagName('range');
    $b=$xmlDoc->getElementsByTagName('description');

    $q=$_GET["q"];

    $hint="";
    $results = array();

    for($i=0; $i<($x->length); $i++) 
    {
        if(stristr($x->item($i)->nodeValue,$q))
        {
            array_push( $results, $i );
        }
    }

    foreach( $results as $result )
    {
        echo '  <div>';
        echo '      <h1>'.$x->item($result)->nodeValue.'</h1>';
        echo '      <p>Type: '.$y->item($result)->nodeValue.'<br>';
        echo '      Time: '.$z->item($result)->nodeValue.'<br>';
        echo '      Range: '.$a->item($result)->nodeValue.'<br>';
        echo '      Description: '.$b->item($result)->nodeValue.'</p>';
        echo '  </div>';
    }
?>

Currently they are all echoed back as a single string. I'm not quite sure how I can separate each line of the string into its own Div.

Does anyone know how to do this? Any hint in the right direction would be really appreciated.

  • 写回答

1条回答 默认 最新

  • donglu1973 2015-11-05 18:42
    关注

    Mike Brant's answer in the comments is to instead return json that can be modified with Javascript. This is a much easier solution. Thanks!

    评论

报告相同问题?