[英]fetch JSON data using jQuery and validate it
我最近一直在使用jQuery,但從未將JSON與它一起使用。
現在,我正在服務器端使用PHP准備JSON。 我需要使用javascript來獲取JSON數據(使用jQuery的首選方式)
我可以通過轉到下面提到的類似URL來獲取JSON數據
http://www.example.com/getjson.php?catid=1
OR
http://www.example.com/getjson.php?catid=15
我的服務器上有一個文件名“ getjson.php”,它將接受“ get”參數作為catid(代表類別ID),從類別表中獲取數據,並以JSON格式輸出數據。
現在,我需要JS代碼(如果代碼在jQuery中,那么將增加我的優勢,因為我非常需要jQuery中的代碼)可以從上述URL中獲取數據並進行解析(我相信這是對JSON解碼,對嗎?)。
還有一件事,在獲取數據之后,我需要驗證接收到的數據是否為JSON格式(這很重要)
類別表具有以下字段,我以JSON格式輸出。
ID, Name, Description, ImageURL, Active, Deleted
請幫幫我。 謝謝。
您可以使用JQuery get函數來請求服務器頁面並傳遞相關參數。
然后,可以使用JSON.parse()
來解析響應,如果它返回/拋出錯誤,則說明您沒有有效的JSON。
注意一旦您的響應通過JSON.parse運行,它將不再是json字符串,而是JavaScript對象。
$.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
}
});
使用$ .getJSON(url,data,callback);
它從給定的URL獲取數據,並檢查其是否為JSON有效。
$.getJSON(
'http://www.example.com/getjson.php?catid=' + $('#valueContainer').val(),
function (data) {
// do stuff here
});
您可以使用以下內容檢索JSON:
$.getJSON('http://www.example.com/getjson.php?catid=1', function(data) { // success statement here });
然后,您可以使用jQuery.parseJSON()
驗證結果。 有關更多詳細信息,請參見http://api.jquery.com/jQuery.parseJSON/ 。
$.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對象 ,所以可以附加一個錯誤回調,如下所示:
$.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-Requested-With標頭,其值為“ XMLHttpRequest”。 您可以使用服務器端PHP代碼檢查此標頭,然后決定是顯示HTML頁面還是發送回適合AJAX的數據。
當您綁定到鏈接上的click事件時,這很有用。 但是,當某人直接導航到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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.