简体   繁体   中英

populating a jQuery Select2() control with JSON data from PHP

I have done the same thing several times (also on the same project actually) and it works fine. I have an issue just with this instance of the same code. First of all I select some data from a db table:

$azioni = $pdo->query("SELECT id_az, concat_ws('-',Descrizione, RGE) as descrizione 
                       FROM azioni_head 
                          JOIN sofferenze ON sofferenze.id_soff = azioni_head.id_soff
                        ORDER BY Descrizione")
               ->fetchAll(PDO::FETCH_ASSOC);

This gives me an array like this (just first few items):

Array
(
    [0] => Array
        (
            [id_az] => AZ000000126
            [descrizione] => Acciaierie Weissenfels S.p.A.-n/d
        )

    [1] => Array
        (
            [id_az] => AZ000000017
            [descrizione] => Acofer S.p.A.-n/d
        )
)

Then I convert this array in a Json array doing: var azioni = <?php echo json_encode($azioni); ?>; var azioni = <?php echo json_encode($azioni); ?>; and finally I populate a Select2 using these data but this time the select2 has no items inside. If I try to view the array once it is encoded using alert(azioni.join( )); I get:

[object Object],[object Object],[object Object],[object Object],

Finally I run:

$('#cod_az').select2({ placeholder: "Scegli", data: azioni });

What is wrong? Why I cannot use this array to populate Select2 with the data? It works in other section of my application!

Edit this is the result of console.log(azioni) in firebug:

[
Object { id_az="AZ000000126",  descrizione="Acciaierie Weissenfels S.p.A.-n/d"}, 
Object { id_az="AZ000000017",  descrizione="Acofer S.p.A.-n/d"}, 
Object { id_az="AZ000000039",  descrizione="ADANI SAS DI ADANI PAOLO & C. S.p.A.-n/d"}, 
Object { id_az="AZ000000019",  descrizione="Administration Speciale ...NG S.A. en faillite-n/d"}
]

To debug, use console.dir(azioni); to inspect your objects.

Change your id_az and descrizione keys to id and text

var data = [{ id: 0, text: 'item1' }, { id: 1, text: 'item2' }];

$(".js-example-data-array").select2({
  data: data
})

https://select2.github.io/examples.html

By default jquery select2 expects data to be in id/text format.

That's the standard and desired behavior. What you want is examine the content of the object instead of getting the [object Object] string, which is the correct result of the toString() method.

There are several ways to examine a structure of arrays and objects in Javascript. What I do is pretty simple and works well but it has a slight twist in it.

var data = JSON.parse(input);
// data now contains the JSON data
// to print it on-screen I do:
alert(JSON.stringify(data));

This might sound strange to re-code the data into JSON, but you have done a full turn in:

  • parsing JSON
  • rendering JSON

So you really can be confident that the input string is valid JSON and what you see in the alert() is the actual content. I don't know an easier method than this.

EDIT: Mind you, it is not the same as printing the input string directly. The decode/recode turn-around really does a lot for you: it shows that it can decode the JSON and shows you how it actually is after decoding. For example, the order of properties is not preserved.

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