Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the json return value

If I can get the following string

([{"data":{"id":"1","user_name":"tutor","book":"123","role":"Tutor"}}]);

How can I alert it? data.user_name show undefined.

    $.getJSON('http://mydomain.com/getmyDetail.php?jsoncallback=?', function(data) {   
        alert(data.user_name);    
    });
    }

another question, if I would like to put some value to the URL, such as

http://mydomain.com/getmyDetail.php?username=XXX&role=XXX

, how to put into getJSON function, directly

$.getJSON('http://mydomain.com/getmyDetail.php?username='+username'+'&role='+role+'&'jsoncallback=?' ?

like image 979
HUNG Avatar asked Nov 30 '25 08:11

HUNG


2 Answers

The [{ means that this is nested in a single element array. On top of that, the highest level key of the element is data. Use:

alert(data[0].data.user_name);
like image 129
Explosion Pills Avatar answered Dec 02 '25 21:12

Explosion Pills


In your example, data is the variable name for the whole response, and you need the user_name element inside the data element, so you should probably try something like

alert(data[0].data.user_name);
like image 44
Nick Andriopoulos Avatar answered Dec 02 '25 22:12

Nick Andriopoulos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!