[英]json parsing single quotes to javascript
hava php array something like this: 哈瓦PHP数组是这样的:
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
并且需要发送此数组以像json_encode()一样查看,但
Uncaught SyntaxError: missing ) after argument list
出现错误: Uncaught SyntaxError: missing ) after argument list
and when looking to error place it looks like this 当寻找错误的地方时,它看起来像这样
my php code looks like this: 我的PHP代码看起来像这样:
$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: 和JS代码:
var models = $.parseJSON('{!!$models!!}');
As far as i know you can place the array inside JavaScript using json_encode()
(see php.net ). 据我所知,您可以使用
json_encode()
将数组放入JavaScript中(请参阅php.net )。
Simply use something like the following PHP: 只需使用类似以下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. 如果json是html输出/内容的一部分,则无需解析json。
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: 补充@JustOneUnderMillions和@RemcovanOs的答案,我制作了这个PHPFiddle,它显示了一个有效的示例:
http://phpfiddle.org/main/code/sm1x-zu6d 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.