Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - Getting data out of this array in JS

Finally i get some output out of PHP instead of just the word "array". This took me a day, AAAAHHHH.

(see here for the solution)

So this is the return value from a XMLHTTP request (to PHP), via a callback in JS. I got it with print_r in PHP.

I post a snippet of the results here. My new question:

  • what is this data structure made of?
  • how to get elements out of this structure, such as CourseID (in JS)?

    [0] => ParseParseObject Object
    (
        [serverData:protected] => Array
            (
                [CourseID] => DEMO2
                [EndDate] => DateTime Object
                    (
                        [date] => 2017-03-31 10:26:00.000000
                        [timezone_type] => 2
                        [timezone] => Z
                    )
    
                [InfoTitle1] => Welcome
                [InfoText1] => Welcome to your course, called "sense & sales". 
                [Admin] => Remco@Demo1
            )
    

My PHP code is

function getGroups(){
  $query = new ParseQuery("CourseInfo");
 $query->equalTo("Admin", "Remco@Demo1");
 $results = $query->find();


// echo $results      // this lead to the string "array"
//print_r($results);  // this leads to the complicated array
//echo "<script>
 var phpOutput = " . json_encode($results) . ";
 console.log(phpOutput);
</script>";
// this leads to [{},{}]; 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want is a JavaScript Object, so you need to use JSON.

(JSON means JavaScript Object Notation.)

PHP has a json_encode function, which will do the work for you: (http://php.net/manual/en/function.json-encode.php)

json_encode — Returns the JSON representation of a value

Try this:

PHP:

echo "<script>
 var phpOutput = " . json_encode($output) . ";
 console.log(phpOutput);
</script>";

Press F12 in your browser to open the browser's Console log window in Developer Tools to see the new JavaScript Object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...