简体   繁体   中英

Outputting Array Data in JS

I have scoured the internet looking for a working method to achieve what i need to, but had no luck so far.

Basically, I have an AJAX request which runs a database query and echo's everything into a json_encode function doo-dah -> echo json_encode($row);

Now, this is then passed back to my Javascript, and this is where i'm stuck. I need to access the JSON array and select various parts for use to alter input field values dynamically. This is the code i have to run the AJAX request and retrieve the JSON array.

var vars = new XMLHttpRequest();
    vars.onload = function() {
        var retrieved = new Array(this.responseText);
        document.getElementById("testingOutput").innerHTML = retrieved;
};

vars.open("GET", "https://my.url.here", true);
vars.send();

Below is what I have tried with no success (Novice to JS..)

var forename = retrieved['first_name']; // Didn't work
var forename = retrieved[1]; // Didn't work either

I have also tried 'for' loops, which haven't worked either (cannot locate the example i copied off..). I was at first trying to set the retrieved var to just (this.responseText) with no luck either. I literally just need a way that i can pull out parts of the array to stick into some jQuery like below:

$("#firstname").val = forename;
$("#lastname").val = surname;

(where 'forename' and 'surname' are the js variables from the array..)

Any help is appreciated as i am losing my mind!!

EDIT: When i was just using var retrieved = (this.responseText); , when i used typeof it said that the type was a string.. and var retrieved = new Array(this.responseText) comes back as an object.. I'm not sure how to access either.

It looks like you're sending JSON , so you'll need to parse that JSON in your JavaScript to make it into a native object

var retrieved = JSON.parse(this.responseText);

You can read more about JSON.parse here


As suggested by kiltek it is also a good idea to use console.log or console.dir when debugging so you can view the data structure you are working with

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