我正在尝试使用 JSON 和 PHP 进行一些操作,但有些事情我找不到方法来做,尽管我不能 100% 确定有方法。但因为它看起来是一个不错的选择(如果可能的话),我决定在这里提问。
我有来自 jquery 官方网站的这些示例。有两个文件,第一个是 index.php,我在其中执行 Ajax,它是:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
$("#fullresponse").html("Full response: " +res);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
一点也不复杂。我有我的 simpleformSubmi.php ,它是:
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile);
error_log("\n", 3, $logFile);
//header("Content-type: text/plain");
foreach ($res as $key=>$value)
{
$str[] = $value;
}
$functionArray ="function(){ \$a = 10; echo \$a;}";
$jsStr = $str[0][1];
echo json_encode($jsStr['firstname']);
echo '<hr />';
echo json_encode($res);
echo '<hr />';
echo json_encode($functionArray);
?>
正如你所看到的 $functionArray - 实际上是一个包含 PHP 函数的字符串,我想使用 JSON 返回并在之后执行它。那么有没有办法真正做到这一点呢?现在我在执行文件后在index.php中得到的是:
“function(){ $a = 10; echo $a;}
”
谢谢 学习者
最佳答案
您似乎正在尝试通过 JavaScript 执行 PHP 函数。由于 PHP 是在服务器端执行的,因此在该上下文中执行 PHP 函数的唯一方法是要求服务器返回为您执行该函数,例如通过执行另一个 ajax 调用。
类似这样的事情:
index.php
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
//Change post() success callback function to executePHP()
$.post('simpleformSubmi.php', { data: dataString}, executePHP, "text");
//Let's define executePHP() outside post() call for clarity
function executePHP()
{
//Ask the server to execute function foo(), and get the result
$.get("example.com/somefile.php?function=foo", function(data)
{
//Success function, do whatever you want.
alert(data);
});
}
});
然后,在 somefile.php 中
<?php
//Condition(s), if any. You could even implement this interface using REST.
//Get function to execute
if($_GET["function"] == "foo")
{
//Output function's result.
echo foo();
}
//The function you want to run
function foo()
{
//Do something
$a = 10;
return $a;
}
?>
如果一切顺利,当 JavaScript 到达 alert(data);
语句时,您将看到 10
。
关于php - 从 JSON 执行 PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9904272/