【问题标题】:How to receive and use a json in ajax sended from php? [closed]如何在 ajax 中接收和使用从 php 发送的 json? [关闭]
【发布时间】:2010-11-30 19:19:11
【问题描述】:

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

【问题讨论】:

  • 天哪,你在说什么?
  • 请缩小您的问题范围。

标签: php json


【解决方案1】:

在 PHP 端,使用json_encode() 将您的数据转换为 JSON,并将其写出,然后退出。最好先发送一个内容类型标头,以确保接收端将其识别为 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 */
});

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2018-10-06
      • 2014-07-21
      相关资源
      最近更新 更多