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

时间:2010-11-30 19:19:12

标签: php json

我想从php接收json到ajax并希望在json中访问不同的字段值。

2 个答案:

答案 0 :(得分: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;

在客户端上,最好的办法是使用现有的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 */
});

答案 1 :(得分:4)

在jQuery中,它将实现类似这样的东西:

var user = {};

$.ajax({
  url: 'http://mysite.com/api/user.json',
  data: {'id': '42'},
  success: function(data){user = data;},
});

$('#name').val(user.name);
$('#email').val(user.email);