PHP json_encode 和 javascript 函数

2022-08-30 16:34:19

我需要在PHP中将javascript函数编码为JSON对象。

这:

$function = "function(){}";
$message = "Hello";

$json = array(   
      'message' => $message,
      'func' => $function
);
echo json_encode($json);

输出:

{"message":"Hello","func":"function(){}"}

我想要的是:

{"message":"Hello","func":function(){}}

我可以用json_encode这样做吗?


答案 1

正如Jani所说,这不能直接用JSON实现,但这可能会帮助你:http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/


答案 2

不。JSON 规范不支持函数。您可以编写自己的代码以类似JSON的格式输出它,但它应该可以正常工作。