如何从php发送的ajax中接收和使用json?

sir*_*n k -1 php json

我想从php接收json到ajax并想要访问json中的不同字段值.

tda*_*ers 6

在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)