Taking .get json string, turn into array?

后端 未结 2 937
生来不讨喜
生来不讨喜 2021-01-29 06:46

Im using the following to retrieve a string from php, i would like to know how to make my string into an array.

Jquery

$.get(\"get.php\"         


        
相关标签:
2条回答
  • 2021-01-29 06:49

    You're already getting back something as useful than an array. Let's say your php does this:

    <?php echo json_encode(array('John', 'Mary', 'Joseph')); ?>
    

    Inside your function where you're alerting the data, you can get access to the elements like this:

    alert(console.log(data[0])); //will alert "John"
    alert(console.log(data[1])); //will alert "Mary"
    

    If you need to loop through any of the elements, you can do so like this:

    $(data).each(function(index) {
        console.log(this.toString());
    });​
    
    0 讨论(0)
  • 2021-01-29 07:01

    You are getting JSON out in that callback already. It doesn't look like it because when you "alert" it gets converted to a string that consists of a comma delimited list of the array elements.

    You can see this by doing alert(data instanceof Array); which will spit out "true".

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