简体   繁体   中英

Populate JS array from returned PHP/JSON

I have a JSON encoded array, to which i am returning to an AJAX request.

I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.

Q. How do i place the JSON array contents into a JS array efficiently?

The PHP/JSON Returned to the AJAX

$sql = 'SELECT *
     FROM btn_color_presets
    ';

$result = mysqli_query($sql);

$array = array(); // 

while($row = mysql_fetch_assoc($result)) // 
{
     $array[] = $row;
     $index++;
}

header("Content-type: application/json");
echo json_encode($array);

You can use JSON.parse function to do so:

var myObject = JSON.parse(response_from_php);

// loop over each item
for (var i in myObject) {
    if (myObject.hasOwnProperty(i)) {
       console.log(myObject[i]);
    }
}

You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.

Adding to Safraz answer:

If you're using jQuery , there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json .

Below example shows you simple way to achieve this. There's simple json property accessing ( result.message ), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield .

Example:

//Assuming, that your `json` looks like this:
{
    message: 'Hello!',
    result: 1
}

$.post(
    'example.com',
    {data1: 1, data2: 2},
    function(response){
        console.log(response.message) //prints 'hello'
        console.log(response.result) //prints '1'

        //iterate throught every field in json:
        $(response).each(function(index, value){
            console.log("key: " + index + " value: " + value); 
        });
    },
    'json'
)

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