Javascript 如何执行PHP标记中的JS函数?
我在一个名为Javascript 如何执行PHP标记中的JS函数?,javascript,php,html,reactjs,react-native,Javascript,Php,Html,Reactjs,React Native,我在一个名为test.php的文件中有以下代码,其任务是创建一个JSON对象并将其传输到JS中的函数 <!DOCTYPE html> <html lang="en"> <head> <title>Payment Receipt</title> </head> <body> <?php $result = $stmt->get_result(); $row = $result
test.php
的文件中有以下代码,其任务是创建一个JSON对象并将其传输到JS中的函数
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
var msg = {$encodedJSON};
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');'
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
alert(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
付款收据
假设$myjson
包含php
中的json
字符串,那么
var msg = {$myJSON};
要更好地理解上述代码,相当于:
var msg = JSON.parse('{$myJSON}')
是将其从php变量转换为js对象的方法
请参阅代码中的注释以获取更多帮助
请运行下面的代码并查看console.log
如何打印json
对象:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
//started with hard coded data to show a working copy paste example
$row = array('date'=>'09-Oct-2020','txnid'=>1234,'atomid'=>456,'amount'=>21345);
if($row) {
$obj = new stdclass(); //op should add this to avoid warning
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
//to see the json encode value in php
//var_dump($myJSON);
//this is not needed in op code
//$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
//php json string is converted to js object here
var msg = {$myJSON};
//see msg object printed in console
console.log(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
付款收据
我通常会这样做:1。与您所做的类似,除了在变量中(例如,$jsString=“”;然后在标记中回显字符串。或2.正常编写JS代码(外部在另一个JS文件中或在HTML中),并在PHP中设置全局样式变量。因此,JS代码(在任何地方编写)使用PHP视图/文件中定义的变量…无论什么(例如var jsCode='注意:PHP在JS之前执行,因此JS不会在PHP代码内运行。PHP在服务器上执行。您不能在服务器上调用诸如postMessage之类的浏览器API。JSON已经是有效的JavaScript(因此得名),是否不需要解码任何内容:var msg=$myJSON;
。