2011-06-22 25 views
1

我最近一直在使用jQuery,但從未使用過JSON。使用jQuery獲取JSON數據並驗證它

現在,我準備在服務器端使用PHP的JSON。我需要使用JavaScript(使用jQuery首選方式)

我可以去下面

http://www.example.com/getjson.php?catid=1   
        OR 
http://www.example.com/getjson.php?catid=15  

提到類似的URL獲取JSON數據有一個文件名爲「getjson.php」上,以獲取該JSON數據我服務器,它將接受'get'參數作爲catid(代表類別id),從類別表中提取數據,並以JSON格式輸出數據。

現在我需要JS代碼(如果代碼將在jQuery中,它會增加優勢,因爲我非常需要jQuery中的代碼),它可以從上面提到的URL獲取數據,並解析它(我相信它是解碼JSON , 對?)。

一兩件事,獲取數據後,我需要驗證,我收到的數據是否是JSON格式或沒有(這真的很重要)

分類表有以下字段,其中我outputing以JSON格式。

ID, Name, Description, ImageURL, Active, Deleted 

請幫我一把。謝謝。

+1

退房jQuery的$ .getJSON();方法。 – Seth

回答

0

使用$ .getJSON(url,data,callback);

它從給定的URL獲取數據並檢查它是否是JSON有效的。

$.getJSON(
    'http://www.example.com/getjson.php?catid=' + $('#valueContainer').val(), 
    function (data) { 
     // do stuff here 
    }); 
0

您可以使用JQuery get函數來請求您的服務器頁面並傳遞相關參數。

然後解析您的回覆,您可以使用JSON.parse(),如果它返回/拋出錯誤,您沒有有效的JSON。

注意一旦您的響應已經通過JSON.parse運行,它將不再是json字符串,它將成爲一個JavaScript對象。

0
$.ajax({ 
    dataType: 'json', 
    type: 'GET', 
    url: 'http://www.example.com/getjson.php?catid=15', 
    success: function(data) { 
     // data be a javascript object that contains your already decoded json data 
    } 
}); 
0

您可以使用以下方法來檢索JSON:

$.getJSON('http://www.example.com/getjson.php?catid=1', function(data) { // success statement here }); 

然後,您可以使用jQuery.parseJSON()來驗證結果。有關更多詳細信息,請參閱http://api.jquery.com/jQuery.parseJSON/

0

$.getJSON應該做的伎倆。

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){ 
    console.log(data); // display the JSON data in the web console 
}); 

因爲$.getJSON回報jqXHR object可以附加一個錯誤回調如下:

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){ 
    console.log(data); // display the JSON *data* in the web console 
    // you can then access the params via dot syntax like this: 
    var id = data.ID, 
     name = data.Name, 
     description = data.Description, 
     imageURL = data.ImageURL, 
     active = data.Active, 
     deleted = data.Deleted; 
}).error(function(){ 
    alert("Error!"); 
}); 

有趣的事實:當你使用jQuery的AJAX它增加了一個X-要求,隨着標頭請求的值「XMLHttpRequest」。你可以用你的服務器端PHP代碼來檢查這個頭文件,並決定你是否應該顯示一個HTML頁面或者發回相應的AJAX數據。

當您綁定到鏈接上的點擊事件時,這非常有用。但是,當有人直接導航到href時,您希望鏈接仍然有效。

<a href="http://www.example.com/getjson.php?catid=1">Category 1</a>  

JS:

$("a").click(function(e){ 
    // Keep the browser from navigating to the link's href. 
    e.preventDefault(); 

    // Because we are using one of jQuery's AJAX methods we can get data back from 
    // our server that is different than the data we would get if we navigated to 
    // the link directly. 
    $.getJSON(this.href, /* optional data param */ function(data){ 
     console.log(data); // display the JSON data in the web console 
    }); 
}); 
相關問題