PHP:使用来自php的参数调用javascript函数 [英] PHP: calling javascript function with parameters from php
问题描述
我试图用PHP变量的参数调用JavaScript函数。
我尝试了两种方法。
I am trying to call JavaScript function with parameter that are PHP variables. I have tried 2 approaches.
-
使用echo
中的script标签在PHP中调用JavaScript函数
calling JavaScript function in PHP with script tags in echo i.e
<?php
echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>';
?>
将PHP变量赋值给JavaScript变量
assigning PHP variables values to JavaScript variables
<script>
var lat="<?php echo $lat;?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
</script>
函数被调用,因为我从页面源进行交叉检查,但传递的参数未定义。
在第二种情况下,值被成功保存在JavaScript变量中,通过alert()来检查,但函数没有被调用。
In first case function is called as I cross-checked from page source but parameters passed are undefined. And in 2nd case values are successfully saved in JavaScript variables, check it by alert(), but function is not called.
这是整个代码:
Here is the whole code:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<?php
if( isset($_POST['lat']) && isset($_POST['lang']) && isset($_POST['zoom']) && isset($_POST['city'])):
$lat=$_POST['lat'];
$lang=$_POST['lang'];
$zoom=$_POST['zoom'];
$city=$_POST['city'];
$zom=(int)$zoom;
var_dump($lang);
var_dump($lat);
//var_dump($zoom);
var_dump($zom);
//echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>';
endif;
?>
<script>
var lat="<?php echo $lat; ?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
</script>
<script>
function initialize(a,b,zom){
if (!a || !b ||!zom){
alert('came on not' +a+b +zom);
// var centerLoc=new google.maps.LatLng( 33.61701054652337,73.37824736488983);
zoom=16;
}
else
{
alert('came');
var zoom =parseInt(zom);
var centerLoc=new google.maps.LatLng(a,b);
}
var mapProp = {
center:centerLoc,
zoom:zoom,
//mapTypeId:google.maps.MapTypeId.ROADMAP
mapTypeId:google.maps.MapTypeId.SATELLITE
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
marker=new google.maps.Marker({
position:centerLoc,
title:'Click to zoom'
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(map.getZoom()+1);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style= "background-color:gainsboro;">
<form method="POST" action="myPage.php" >
Enter latitude: <input type ="text" name="lat" id="lat" / ><br/>
Enter longitude: <input type ="text" name="lang" id="lang"/ ><br/>
Enter City Name: <input type="text" name="city" id="city"/><br/>
Enter Zoom level: <input type ="text" name="zoom" id="zoom"/ ><br/>
<input type="button" value ="Perview" onclick=" initialize(
document.getElementById('lat').value,
document.getElementById('lang').value,
document.getElementById('zoom').value)"/>
<input type="Submit" value="Save" />
</form>
<center><div id="googleMap" style="width:1000px;height:500px;"></div></center>
</body>
</html>
推荐答案
使用 json_encode()
。如果你不这样做,那么在你从PHP到HTML / JS层传递数据时,你将永远有可能错误地将你的数据转义。
Use json_encode()
. If you don't there will always be the possibility you escaped your data incorrectly as it passes from the PHP to the HTML/JS layer.
$vars = array($lat, $lang, $zoom);
// JSON_HEX_TAG and JSON_HEX_AMP are to remove all possible surprises that could be
// caused by vars that contain '</script>' or '&' in them. The rules for
// escaping/encoding inside script elements are complex and vary depending
// on how the document is parsed.
$jsvars = json_encode($vars, JSON_HEX_TAG | JSON_HEX_AMP);
echo "<script>initialize.apply(null, $jsvars)</script>";
一般来说,为了您的理智,PHP中需要提供给js的所有数据运行在当前页面上应该被收集到一个PHP数组中,然后放入一个js对象中。例如:
In general, for your sanity, all data that is in PHP that you need to make available to js running on the current page should be collected into a single PHP array and then placed into a single js object. For example:
<?php
$jsdata = array(
'formvars' => array(
'lat' => $lat,
'lang' => $lang,
'zoom' => $zoom
),
'username' => $username,
'some_other_data' => $more stuff
);
?>
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
initialize(JSDATA.formvars.lat, JSDATA.formvars.lang, JSDATA.formvars.zoom);
</script>
现在JS和PHP / HTML图层之间只有一个单一的联系点,所以您可以轻松地跟踪您将要放入JS命名空间的内容。
Now there is only a single point of contact between the JS and PHP/HTML layers so you can easily keep track of what you are putting into the JS namespace.
这篇关于PHP:使用来自php的参数调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!