Benjamin Lawson Benjamin Lawson - 6 months ago 9
Javascript Question

How can I parse specific parts of my AJAX array in Javascript?

I used AJAX to send back an array with many variables worth of data to my page to have displayed. The array looks something like this right now:

{"dateName":"05/18/2016","hour1":null,"hour2":null,"hour3":null,"hour4":null,"hour5":null,"hour6":null,"hour7":null,"hour8":null,"hour9":null,"hour10":null,"hour11":null,"hour12":null,"hour13":null,"hour14":null,"hour15":null,"hour16":null,"hour17":null,"hour18":null,"hour19":null,"hour20":null,"hour21":null,"hour22":null,"hour23":null,"hour24":null}


Now I am displaying the parts of the array in my data boxes using

//AJAX Data
success: function(data) {
var array = data.split(",");
$("#date").html(array[0]);
i = 0;
while (i < 25) {
$("#hour"+i).html(array[i]);
i++;
}


This displays data that looks like this on my webpage


"hour1":"sleep"


As you can see, the variable name in quotes and the variable value that was passed through ajax. But I only want


sleep


displayed (no quotes, no variable) . How do I get the variable name and quotes out of my displayed data?

Thank you so much!

Answer

use this

$.ajax({url: "demo_test.txt", success: function(result){
       // $("#div1").html(result);


        var parsed = JSON.parse(result);
        alert(parsed["hour1"]);
    }});
Comments