将JSON数据检索到Javascript的指南

时间:2011-11-18 17:49:45

标签: javascript jquery ajax json multidimensional-array

我在这里和谷歌搜索过,但作为一个没有经验的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?

提前致谢。 皮特

3 个答案:

答案 0 :(得分:2)

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/

答案 1 :(得分: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请求的不同方法。

答案 2 :(得分:2)

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

(ii)jQuery将非常容易地获取和解析JSON,尽管还有其他库可以执行此操作。然而,许多人因其可用性而提倡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/