【问题标题】:Guidance for retrieving JSON data into Javascript将 JSON 数据检索到 Javascript 的指南
【发布时间】:2012-01-01 11:16:28
【问题描述】:

我在这里和谷歌上搜索过,但作为一个没有经验的 Javascript 黑客,我正在努力寻找一个我认为是相当直接的行动的好例子。

我有一个服务器端脚本,我已对其进行编码以提供 JSON 格式的输出 (content.php?action=json)。

JSON 输出是多维的,即格式化为 ...

 [Content]
   [Class 1]
     [Entry 1]
     [Entry 2]
     [Entry 3]
      ...
  [Class 2]
     [Entry 1]
     [Entry 2]
      ...

类和条目的数量都是可变的。

我现在正在尝试编写一个简单的 Javascript 来执行以下操作...

1) Call my PHP script
2) Copy the returned JSON output into a suitable Javascript array
3) Display parts of this array within my HTML pages

这个谜题有很多“片段”,但我很难把它们放在一起。有人可以为我举一个简单的例子吗?

几个附带问题...

(i) Does the output file containing the JSON data need to have it's HTML headers altered to indicate it's content type?
(ii) Is jQuery the best approach for this sort of thing?

提前致谢。 皮特

【问题讨论】:

标签: javascript jquery ajax json multidimensional-array


【解决方案1】:

jQuery 确实为 ajax 调用提供了一种非常简单的方法:

$.ajax({
    url: '/path-to-php-script',
    type: 'get',
    dataType: 'json',
    success: function(json) {
        // gets run after ajax call is successful
        // do stuff with json object
        // format: json.content.class[0].entry[2]
    }
});

提供dataType: 'json' 会自动将来自您的php 脚本的响应评估为一个json 对象。

这里是关于 ajax 调用的 jQuery 文档:http://api.jquery.com/jQuery.ajax/

【讨论】:

  • 我想我会指出有一点错字,在'json 之后缺少结束'
【解决方案2】:

您可以在创建 json 数据时控制它的格式,这样您就不需要在检索到它后将其复制到数组中。

$.get("your_php_script.php",
   function(data){
      // update html with json ( in data )
   }, "json");

http://api.jquery.com/jQuery.get/

回答你的附带问题

i) json 的内容类型是 application/json ii) jQuery 是一种很好的(并且流行的)检索 json 的方法,因为它抽象了浏览器发出 ajax 请求的不同方法。

【讨论】:

    【解决方案3】:

    (i) 内容类型可以只是纯文本。不过要正确,请参阅What is the correct JSON content type?

    (ii) jQuery 将使获取和解析 JSON 变得非常容易,尽管还有其他库也可以做到这一点。不过,由于 jQuery 的易用性,许多人提倡使用 jQuery。

    现在使用 jQuery 回答您的主要问题:

    $.getJSON('content.php?action=json', function(data) {
        // data returns the result of the request, and will be the array
    });
    

    http://api.jquery.com/jQuery.getJSON/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多