JSON_encode PHP数组准备好jQuery自动完成

I'm trying to pass a PHP array to my view, and then use that array to populate jQuery autocomplete.

foreach ($products as $product)
{               
    $productsArray[] = array('label' => $product->getName()  ,'id' => $product->getId() , 'value' => $product->getUrlSafeName());                           
}

$productsJson = json_encode($productsArray);

$productsJson then gets passed to the view, where I insert it into the DOM. I'm using Twig as my templating engine:

<div id="autocompleteData">{{ productsJson }}</div>

and then my jQuery:

$( document ).ready(function() {

    var autocompleteData = $('#autocompleteData').text();       

    $('#findoffice_location').autocomplete({ 
         source: autocompleteData,
         change: function (event, ui) {  } });

});

If I console.log autocompleteData, it 'looks' like a JSON object in structure, but isn't.

If I do:

var autocompleteData = [{"label":"Toybox","id":1,"value":"toybox"},{"label":"Shoe","id":2,"value":"shoe"},{"label":"Eggs","id":3,"value":"eggs"}];

and then consolelog , each autocompleteData product is a proper JSON object, and autocomplete works as expected.

You need to convert the string output of .text() to JSON:

source: jQuery.parseJSON(autocompleteData)

When you enter it manually, you're feeding in actual JSON, hence why it works.

Try and wrap autocompleteData in a call to $.parseJON like this:

$( document ).ready(function() {

    var autocompleteData = $('#autocompleteData').text();       

    $('#findoffice_location').autocomplete({ 
        source: $.parseJON(autocompleteData),
        change: function (event, ui) {  } });

});

Edit @George beat me to it.