简体   繁体   English

PHP json_encode在gulp中不起作用

[英]php json_encode is not working in gulp

I am using laravel 5.2 , I am using like below 我正在使用laravel 5.2,我正在使用如下

var data = <?php json_encode($data['value']); ?>

when I am using JavaScript code below in the blade file, then its working fine, but when I am using the code as a separate file and trying to gulp that , then it is not working , my data is not loading 当我在刀片文件中使用下面的JavaScript代码时,则可以正常工作,但是当我将代码用作单独的文件并尝试吞入该代码时,则它不起作用,则无法加载我的数据

var data = "<?=json_encode($data['value']);?>"

or 要么

var data = "<?php echo json_encode($data['value']);?>"

You are not echoing out the value, your var is null 您没有回显值,您的var为null

Other mate already provided the correct solution specially @user1779617, now i am explaining with a basic example: 其他伴侣已经专门提供了正确的解决方案@ user1779617,现在我用一个基本的例子进行说明:

<?
// a simple array
$data['value'] = array(1=>'test');
$encodedData = json_encode($data['value']);
?>

<script type="text/javascript">
var data = <?=$encodedData?>;
console.log(data); //  Object { 1="test"}
</script> 

If you have posted original code than you have an error in your javascript , you miss the ending termination semicolon (;) plus you need to echo the result as other mentioned in answers. 如果您发布的原始代码比javascript错误,那么您会错过结尾的终止分号 (;) ,并且需要echo显结果,如答案中提到的其他。

UPDATE 1 更新1

if you are still facing the same issue than use JSON.parse in javascript 如果您仍然面临与在javascript使用JSON.parse相同的问题

<script type="text/javascript">
var data = JSON.parse( ' <?=$encodedData?>');
console.log(data); //  Object { 1="test"}
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM