2016-04-26 60 views
2

在閱讀大量的帖子後,我仍然無法使用Jquery讀取mySQL字段。我的PHP代碼,它連接到一個數據庫,並得到了一些數據,輸出採用echo json_encode($html);如下:使用Ajax和PHP訪問mySQL字段

{"id":"1","title":"this_is_title","description":"this_is_description","url":"this_is_url"} 

我再嘗試讀取單個字段,但我不斷收到「未定義」。例如:

$.getJSON("get.php", function(result) { 
    $.each(result, function(key, field){ 
     console.log(field.title); 
    }); 
}); 

如果我只是使用的field代替field.title它的工作原理,但我得到的所有領域(當然)。

回答

0

你的JSON數據只包含一個對象,而不是對象的數組。

你迭代這個JSON對象中的每個屬性與$.each,這樣的回調函數key內將屬性名和field將物業

您的控制檯日誌呼叫改變這樣:

console.log(field); 

,你可以看到其中的差別,該值將財產將被記錄。如果只有一個單一的對象返回,那麼你可以輕鬆地訪問每個字段

$.getJSON("get.php", function(result) { 
    console.log(result.id); 
    console.log(result.title); 
    // etc 
}); 
+0

好的,很好。但我如何通過字段名稱訪問mySQL字段?我看到使用記號'field.title'的代碼。 – Nicero

+0

您不需要使用'$ .each'來迭代它們。刪除該部分,只使用'result.id','result.title'等 – danjam

0

試試這個,使用parseJSON然後嘗試訪問:

$.getJSON("get.php", function(result) { 
    var obj = JSON.parse(result); 
    $.each(obj, function(key, field){ 
    console.log(key); // here you will get index like id,title 
    console.log(field); // here you will get value 
    }); 
}); 
+0

我得到了 - > SyntaxError:JSON.parse:JSON數據第1行第2列的意外字符。 Json數據可能在哪裏出錯? – Nicero

+0

好的嘗試var obj = JSON.parse(結果) –

+0

我也更新了答案,也看看那個 –

3

您可以直接訪問JSON的屬性,像這樣。 你已經知道這些字段的名稱,所以使用它們。

$.getJSON("get.php", function(result) { 
    console.log(result.id); 
    console.log(result.title); 
    console.log(result.description); 
    console.log(result.url); 
});