在PHP方面,用于json_encode()将数据转换为JSON,并将其写出,然后退出.Best首先发送内容类型标头,以确保接收端将其识别为JSON:
<?php
$response_data = whatever_function();
$response = json_encode($response_data);
header("Content-type: text/json");
echo $response;
exit;
Run Code Online (Sandbox Code Playgroud)
在客户端上,最好的办法是使用现有的AJAX框架,例如jQuery中内置的AJAX功能.假设您的脚本位于http://example.com/ajax.php,并且客户端页面位于http://example.com/ajaxclient.html,一个合适的jQuery片段将类似于:
$.getJSON('ajax.php', { /* GET data goes here */ }, function(data) {
/* data contains the values you sent in your PHP script */
});
Run Code Online (Sandbox Code Playgroud)