pass php array to javascript array

前端 未结 2 1324
慢半拍i
慢半拍i 2021-01-21 19:32

I\'m looking for the best way to pass php array to javascript.

I\'m making a RPG, and when they login, I\'d like to return their saved data from database and store in an

相关标签:
2条回答
  • 2021-01-21 20:11

    If you use $.getJSON and you provide valid json, you don't need to parse anything, so you can change your php to:

    if ($row = $result->fetch_assoc()) {
        echo json_encode($row);
        exit;    // You're limiting the number of rows to 1, so there is no need to continue
    }
    

    And the javascript:

    $.getJSON("php/CRUD.php", {"_functionToRun" : ""},
        function (returned_data) {
            // you can push `returned_data` to an array / add it to an object,
            // but then you need to keep track of its index
            log("1: " + returned_data.experience); //output: `1: 120` 
            log("2: " + returned_data.levelname); //output: `2: mymap2`
        }
    );
    
    0 讨论(0)
  • 2021-01-21 20:26

    What you need to do is, change this code:

    while ($row = $result->fetch_assoc()) {
        $message =  $row['experience'] . $row['levelname'];
    }
    

    To make it as an array:

    while ($row = $result->fetch_assoc()) {
        $message[] =  $row['experience'] . $row['levelname'];
    }
    

    So, $message now becomes an array. You need to output this to the client. You can do that using:

    die(json_encode($message));
    

    The reason is, in your code, it will output only the last one.

    0 讨论(0)
提交回复
热议问题