我在将PHP字符串传递给Javascript函数时遇到问题,我读了很多关于这个问题的帖子,并尝试了几种方法,但没有一个对我有用。 基本上我有两个函数,一个用PHP编写,从数据库中提取信息,另一个用Javascript编写,旨在让我为google地图编写地址并传递一些信息添加到信息窗口,两位代码是如下所示:
PHP
try {
$bubbleData = $dbConnection->getBubbleData();
} catch (Exception $e) {
echo "The following error occoured while attempting to get Google map info window data" .
" " . $e->getMessage() .
" " . "In file" .
" " . $e->getLine() .
" " . "on line" .
" " . $e->getLine();
}
if (mysql_num_rows($bubbleData) == 0) {
echo "No Placement data found to populate map";
} else {
while ($row = mysql_fetch_array($bubbleData)) {
$companyName = $row['Company_Name'];
$title = $row['Title'];
$address_1 = $row['Address_Line_1'];
$address_2 = $row['Address_Line_2'];
$address_3 = $row['Address_Line_3'];
$address_4 = $row['Address_Line_4'];
$post_Code = $row['Post_Code'];
$forename = $row['Forename'];
$surname = $row['Surname'];
$fullAddress = $address_1 . " " . $address_2 . " " . $address_3 . " " . $address_4 . " " . $post_Code;
$partAddress_1 = $address_1 . " " . $address_2;
$partAddress_2 = $address_3 . " " . $address_4;
$infoText = "<h4>" . $title . "</h4>" .
'<b>' . "Company name:" . '</b>' . " " . $companyName .
"</br>" .
"<b>" . "Employee name:" . '</b>' . " " . $forename . " " . $surname . '</br>' .
"<b>" . "Company address:" . "</b>" . " " . $partAddress_1 . '</br>' .
$partAddress_2 . '</br>' . $post_Code;
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(<?php echo json_encode($fullAddress);?>,<?php echo json_encode($infoText);?>);
</SCRIPT>'";
}
}
的Javascript
function geocodeAddress (address,infoText) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loadMarker(results[0].geometry.location,infoText,address);
latlngArray.push(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " +" "+ status);
}
});
}re
现在我知道这两个单独工作正常,但每当我尝试在PHP旁边调用javascript并传递变量时我在firebug中出现以下错误:
属性地址的值无效:
我一直试图让这一切都发生,我使用了正则表达式的平面回声和json_encode()函数,并且没有人能帮助吗?
提前致谢
答案 0 :(得分:4)
您在PHP代码中嵌套了<?php ?>
,这不会被解释为PHP。相反,它只是作为字符串打印到您的输出中。
// Instead of
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(<?php echo json_encode($fullAddress);?>,<?php echo json_encode($infoText);?>);
</SCRIPT>'";
// Change to
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(" . json_encode($fullAddress) . "," . json_encode($infoText) . ");
</SCRIPT>'";
答案 1 :(得分:0)
至少在我的情况下,我注意到了
<?php ...foo... ?>
HTML主体中的段,仅当文件扩展名为.php时才进行php评估。 也就是说,我不得不重命名:
mv foo.html foo.php
将php值传递给javascript变量。