简体   繁体   中英

json parsing single quotes to javascript

hava php array something like this:

array(1) {
    [39]=>
    array(3) {
        [0]=>
        array(2) {
            ["id"]=>
            int(21)
            ["name"]=>
            string(14) "32''LE32HDF3010"
        },
        [1]=>
        array(2) {
            ["id"]=>
            int(22)
            ["name"]=>
            string(14) "40''LE40FHDE3010"
        },
        [2]=>
        array(2) {
            ["id"]=>
            int(23)
            ["name"]=>
            string(14) "40''40FS4610R"
        },

    }
}

and need to send this array to view like json_encode() but getting error like: Uncaught SyntaxError: missing ) after argument list

and when looking to error place it looks like this 在此处输入图片说明

my php code looks like this:

$phone_models = Phone_model::get() -> all();

$models = array();
foreach($phone_models as $model){
    $models[$model -> manufacturer_id][] = array(
        'id' => $model -> id,
        'name' => $model -> name,
    );
}

$models = json_encode($models);

And JS code:

var models = $.parseJSON('{!!$models!!}');

As far as i know you can place the array inside JavaScript using json_encode() (see php.net ).

Simply use something like the following PHP:

<?php
$array = ('foo', 'bar', array('foo', 'bar'))
?>

<script type="text/javascript">

var array = <?php echo json_encode($array); ?>

</script>

This prints the array into a script element.

Just do

var models = <?php echo $models?>;

there is no need to parse the json if it is part of the html output/content.

echo "var xyz = ".json_encode([1,2,3]).";";

becomes

var xyz = [1,2,3];

complementing @JustOneUnderMillions and @RemcovanOs answers, I made this PHPFiddle that shows an working example:

http://phpfiddle.org/main/code/sm1x-zu6d

Code:

<script>
    var json = 
<?php
class Model {
    function __construct($mi, $id, $name) {
        $this->manufacturer_id = $mi;
        $this->id = $id;
        $this->name = $name;    
    }
    public $manufacturer_id;
    public $id;
    public $name;
}

$pmodels = array(new Model(39, 21, "32''LE32HDF3010"), new Model(39, 22, "40''LE40FHDE3010"), new Model(39, 21, "40''40FS4610R"));
$models = array();

foreach($pmodels as $model){
    $models[$model -> manufacturer_id][] = array(
        'id' => $model -> id,
        'name' => $model -> name,
    );
}

$models = json_encode($models);


echo $models;        
?>;
    console.log(json);
</script>

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