[英]How can I parse JSON using the data parameter in JQuery?
我正在使用Jersey和JQuery在客戶端創建Web應用程序。 我具有以下返回JSON字符串的URL:
http://localhost:8080/messenger/webapi/messages/1
返回:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
在瀏覽器中輸入時。
現在,我嘗試使用以下JQuery函數獲取此數據客戶端:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
編輯:當按下“ btnRegister”時,什么都不會顯示
這對我來說毫無意義。
成功回調函數中有一些不必要的$
包裝,也不需要在設置dataType:'json'
解析響應。 為了更好地理解$.ajax()
閱讀此處的文檔。
$(function() { $('#btnRegister').click(function() { var username = $('#username').val(); addMessage(); }); function addMessage() { var url = rootURL; $.ajax({ type: 'GET', url: rootURL + "/1", dataType: "json", // data type of response success: function(data) { //----^----------- remove the $ sign alert('ID: ' + data); } }); } });
您可以使用obj.prop
或obj['prop']
訪問該值
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}; alert(obj.author); alert(obj['author']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.