简体   繁体   中英

passing parameters from php to javascript on same page

I have the following code wherein I'm trying to get values of the xml element 'point' from an RSS feed using PHP. When I display the value of point using 'echo', it gives me the correct data. However, when I pass the same parameter to a javascript function, it calls the function very randomly. The alert in the javascript function gives me the sum of the points of either 2 or 3 point values from each iteration. How do I resolve this problem?

<!DOCTYPE html>
<html>
<head>
    <title>Natural Disasters</title>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=false&amp;libraries=places"></script>
    <script type="text/javascript">
        var i=0;
        function getPoint(point) {

            alert("Value of i : "+i+" Value of point : "+point);
            ++i;
        }
    </script>
    <script>
        function showRSS(str) {
            if (str.length === 0) {
                document.getElementById("rssOutput").innerHTML = "";
                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("rssOutput").innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.open("GET", "getrss.php?q=" + str, true);
            xmlhttp.send();
        }

    </script>
</head>

<body>
    <?php
    $xml2 = ("http://www.volcano.si.edu/news/WeeklyVolcanoRSS.xml?");
    $xmlDoc2 = new DOMDocument();
    $xmlDoc2->load($xml2);
    $x2 = $xmlDoc2->getElementsByTagName('item');
    $i2 = 0;

    foreach ($x2 as $y) {

        $geo_rss = $y->getElementsByTagNameNS("http://www.georss.org/georss", 'point');
        $title = $y->getElementsByTagName('title')->item(0)->nodeValue;
        $point = $geo_rss->item(0)->nodeValue;
        echo ("<h3>" . $title . "</h3>" );
        echo ($point);

        echo '<script type="text/javascript">'
        , 'getPoint(' . $point . ');'
        , '</script>'
        ;
        ++$i2;
    }
    ?>
</body>
</html>

PS :I have followed the same procedure for another set of parameters, and it works perfectly fine. I do not know why this one is not working.

Change your php code to write script as below :

echo '<script type="text/javascript"> getPoint("' . $point . '");</script>';

You just need to wrap $point into double quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM