【问题标题】:php-javascript: cannot update the variablephp-javascript:无法更新变量
【发布时间】:2014-01-29 16:54:43
【问题描述】:

我这样做是为了大学作业。我正在做一个基于 eBay 和谷歌地图 API 的网络应用程序。在实践中,我对 eBay 进行 API 调用,然后将结果放入表格中。现在,单击我得到的每个项目的位置,我想在谷歌地图中对地址进行地理编码。我为 eBay API 编写了 PHP 代码,为 Google Maps API 编写了 Javascript 代码,如下所示:

eBay API 的 PHP 代码

foreach($resp->searchResult->item as $item){
            $_i = 1;

            // Determine which price to display
            if ($item->sellingStatus->currentPrice) {
                $price = $item->sellingStatus->currentPrice;
            } else {
                $price = $item->listingInfo->buyItNowPrice;
            }

            $itemLocation = $item->location;
            // For each item, create a cell 
            $results .= "<tr> \n<td $thisCellColor valign=\"top\"> \n";
            $results .= "<img src=\"$item->galleryURL\"></td> \n";
            $results .= "<td $thisCellColor valign=\"top\"> <p><a href=\"" . $item->viewItemURL . "\">" . $item->title . "</a></p>\n";
            $results .= 'Shipped to: <b>' . $item->shippingInfo->shipToLocations . "</b><br> \n";
            $results .= 'Current price: <b>$' . $price . "</b><br> \n";
            $results .= "Location: <INPUT TYPE=\"button\" id=\"$_i\" VALUE=\"$itemLocation\" onclick='clickToGeocode($_i);'  <br>";
            $results .= "</FORM> \n";
            $results .= "</td> </tr> \n\n";
            $_i = $_i + 1;
        }

谷歌地图的Javascript代码

function clickToGeocode(id){
    var address = document.getElementById(id).value;
    document.write(id);
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
        });
    } else {
        alert('Geocode was not successful for the following reason: ' + status);
    }
    });
}

问题是,每次我尝试对位置进行地理编码时,地图都会转到在 eBay 中找到的第一个项目的位置。我的意思是 $_i(在 PHP 中)和 id(在 Javascript 中)是总是 1..

我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: javascript php google-maps-api-3 ebay-api


    【解决方案1】:

    您每次都将$_i 重置为1。初始值需要设置before循环,而不是within

    $_i = 1;
    
    foreach($resp->searchResult->item as $item)
    {
    

    【讨论】:

    • @MichaelRushton...我做了一个多么愚蠢的问题..我完全错过了这个...谢谢:)
    【解决方案2】:

    您的 html 已损坏:

    $results .= "Location: <input [..snip...] onclick='clickToGeocode($_i);'  <br>";
                                                                            ^---- here
    

    您永远不会关闭 &lt;input&gt; 标签,例如您在指定位置缺少&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      相关资源
      最近更新 更多