PHP:使用来自 php 的参数调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15602276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: calling javascript function with parameters from php
提问by Rabeel
I am trying to call JavaScript function with parameter that are PHP variables. I have tried 2 approaches.
我正在尝试使用 PHP 变量的参数调用 JavaScript 函数。我尝试了 2 种方法。
calling JavaScript function in PHP with script tags in echo i.e
<?php echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>'; ?>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>
使用echo中的脚本标签在PHP中调用JavaScript函数,即
<?php echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>'; ?>将 PHP 变量值分配给 JavaScript 变量
<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>
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.
在第一种情况下,当我从页面源进行交叉检查时调用函数,但传递的参数未定义。在第二种情况下,值成功保存在 JavaScript 变量中,通过 alert() 进行检查,但未调用函数。
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>
回答by Francis Avila
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.
使用json_encode(). 如果你不这样做,你总是有可能在数据从 PHP 传递到 HTML/JS 层时错误地转义数据。
$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>";
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:
一般来说,为了您的理智,您需要提供给当前页面上运行的 js 的所有 PHP 中的数据都应该收集到单个 PHP 数组中,然后放入单个 js 对象中。例如:
<?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>
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.
现在 JS 和 PHP/HTML 层之间只有一个联系点,因此您可以轻松跟踪放入 JS 命名空间的内容。
回答by Pieterjan Stevens
Call the function when the browser finished loading the javascript.
当浏览器完成加载 javascript 时调用该函数。
<script>
window.onload = function() {
var lat="<?php echo $lat; ?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
};
</script>
回答by ATSU EMMANUEL
Just call on the predefined java script code like jsFunction() ; in your php code
只需调用预定义的 java 脚本代码,如 jsFunction() ;在你的 php 代码中
回答by Chris Sprague
I found some really good examples on Calling a javascript function from phpand it appears you can also run the code online at PhpFiddle.org
我发现了一些关于从 php 调用 javascript 函数的非常好的例子,看来你也可以在PhpFiddle.org在线运行代码
Just in case the links break, here are the examples:
以防万一链接中断,以下是示例:
Example 1: Calling without parameters
示例 1:无参数调用
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
?>
<!--This JS function can be defined here or a separate file since so long as it gets created in JS space'-->
<script>
function callAlert(){
alert('A alert without a parameter');
}
</script>
<script>
callAlert();
</script>
<?php
?>
Example 2: Calling with a single parameter
示例 2:使用单个参数调用
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
//Data that is going to be passed into the JavaScript function. Try to keep all vars together so
//that it's easier to track down the php/javascript interaction
$jsdata = 'MyName';
?>
<!--This JS can be here or a separate file since all it's doing is defining a function in the JS space'-->
<script>
function callAlert(text){
alert(text);
}
</script>
<!--This JS must be defined with the php since it's using previously defined php variables -->
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
//Prompt using a single var
callAlert(JSDATA);
</script>
<?php
?>
Example 3: Calling using an array of parameters
示例 3:使用参数数组进行调用
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
$myname = 'MyName';
$yourname = 'YourName';
//Data that is going to be passed into the JavaScript function. Try to keep all vars together so
//that it's easier to track down the php/javascript interaction
$jsdata = array(
'input' => $myname,
'array_input' => array(
'name' => $yourname
),
);
?>
<!--This JS can be here or a separate file since all it's doing is defining a function in the JS space'-->
<script>
function callAlert(text){
alert(text);
}
</script>
<!--This JS must be defined with the php since it's using previously defined php variables -->
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
//Prompt using a single var in the array
callAlert(JSDATA.input);
//Prompt using a var from a nested array
callAlert(JSDATA.array_input.name);
</script>
<?php
?>

