0

I have been playing with JSON/PHP/JS today and I am having problems..

My PHP works fine which gets a row of data from my SQL table then encodes as JSON. My JS/Jquery file loads the data from the PHP file fine using $.getJSON.

However, when i try and use the data later in the page like so: gender = user['player'].gender, I get user.player is undefined.

This is my code that is relevant:

function getUserInfo() {
    var url = "./php/getUserInfo.php";
    $.getJSON(url, function(data) {
        $.each(data.members, function(i, dat) {

            user['player'] = {
                gender: dat.gender,
                fname: dat.first_name,
                lname: dat.last_name,
                username: dat.username,
            };
        });
    });
}

user = {};
getUserInfo();

//Displays an object, which has the correct information I want.
console.log(user);
var gender = user['player'].gender;
console.log(gender);​

the last line of code gives me the error that user.playe is not defined. but it should display male Help would be helpful, I have tried many things to fix this but cant seem to do so.

4

1 回答 1

4

$.getJSON异步的。

发送请求后,它会立即转到下一行,并且不会等待请求完成。

因此,当您尝试访问变量时,它仍然不可用..

尝试将那段代码放在后面$.each,它应该可以工作。

于 2012-11-27T16:35:44.073 回答