简体   繁体   中英

How can I parse JSON using the data parameter in JQuery?

I am making a web application using Jersey and JQuery for client-side. I have the following URL that returns a JSON string:

http://localhost:8080/messenger/webapi/messages/1

returns:

 {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}

when typed into the browser.

Now I am attempting to get this data client-side using the following JQuery functions:

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);

        })
    });
}

});

EDIT: When the "btnRegister" is pressed nothing is displayed at all

which just doesn't make sense to me.

There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json' . For better understanding of $.ajax() read documentation here .

 $(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); } }); } }); 

You can access the value using obj.prop or obj['prop']

 var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}; alert(obj.author); alert(obj['author']); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM