2011-11-18 27 views
2

我已經在這裏和谷歌上搜索過,但作爲一個沒有經驗的Javascript黑客,我正在努力尋找一個我認爲是一個相當直接的行動的好例子。將JavaScript數據檢索到JSON數據的指導

我有一個服務器端腳本,我編碼提供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? 

在此先感謝。 皮特

+0

我寫的Dropbox我自己的JSON輸出的Facebook應用程序。一個工作示例顯示在@ http://apps.facebook上。com/fileglu/technical –

回答

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'會自動從EVAL你的PHP腳本的響應成JSON對象。

下面是關於Ajax調用jQuery的文檔:http://api.jquery.com/jQuery.ajax/

+1

我想我會指出,有一個錯字,錯過了''json'後面的結尾'''。 – jli

+0

Thx!現在應該修好了。 – phixr

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

(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/