js使用php变量
<h3 id="php">php</h3><pre><code class="language-php"><?php
$text = '文本';
$articles = [
[
'title' => '标题1',
'content' => '内容1'
],
[
'title' => '标题2',
'content' => '内容2'
]
];
?>
<script>
//字符串
var text = '<?php echo $text ?>';
console.dir(text);
//数组
var articlesJson = '<?php echo json_encode($articles); ?>';
var articles = JSON.parse(articlesJson);
console.dir(articles);
</script>
</code></pre>
<h3 id="laravel">laravel</h3>
<p><strong>php</strong></p>
<pre><code class="language-php">class TestController extends Controller
{
function test()
{
$data = [];
$data['text'] = '文本';
$data['articles'] = [
[
'title' => '标题1',
'content' => '内容1'
],
[
'title' => '标题2',
'content' => '内容2'
]
];
return view('test/test',$data);
}
}
</code></pre>
<p><strong>js</strong></p>
<pre><code class="language-js"><script>
//字符串
var text = '{{$text}}';
console.dir(text);
//数组
var articlesJson = '{!! json_encode($articles) !!}';
var articles = JSON.parse(articlesJson);
console.dir(articles);
</script>
</code></pre>
<h3 id="结果">结果</h3>
<p><strong>控制台输出结果</strong></p>
<blockquote>
<p>文本<br>
Array(2)<br>
0: {title: "标题1", content: "内容1"}<br>
1: {title: "标题2", content: "内容2"}<br>
length: 2</p>
</blockquote><br><br>
来源:https://www.cnblogs.com/pine007/p/12755292.html
頁:
[1]