简体   繁体   中英

Jquery - Convert string to Array

I am retrieving a string from Database & this string is an Array.

 jq.ajax({
            type: "GET",
            url: "/Method/",
            success: function () {
               // Sample data     
               var data = "[{                                   
                              name: "Santro",
                              canvas: "1"
                             }, {                                       
                              name: "Tata",
                              canvas: "2"
                           }]";

After getting the data by AJAX call, I get the string.

How to convert this string to an Array?

Try this

jq.ajax({
        type: "GET",
        url: "/Method/",
        dataType: "JSON",
        success: function (obj) {
            $.map(obj, function(el) 
               { 
                    return el // as array 
               });
        }

your php should look like this :

 public function actionTest2() {
    $arr[] = [
        'name' => 'saura',
        'canvas' => 1,
    ];
    $arr[] = [
        'name' => 'tat',
        'canvas' => 3,
    ];
  //$arr like your db result 
    echo json_encode($arr);
}

and php output: [{"name":"saura","canvas":1},{"name":"tat","canvas":3}]

your js should look like this:

jq.ajax({
    type: "GET",
    url: "test2",
    dataType: "JSON",
    success: function (data) {
      var obj = jQuery.parseJSON(data);
       console.log(obj[0]); // make loop to navigate the data
    }

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