尚勇 發表於 2020-4-22 19:14:00

js使用php变量

<h3 id="php">php</h3>
<pre><code class="language-php">&lt;?php
        $text = '文本';
    $articles = [
                [
                        'title' =&gt; '标题1',
                        'content' =&gt; '内容1'
                ],
                [
                        'title' =&gt; '标题2',
                        'content' =&gt; '内容2'
                ]
        ];
?&gt;

&lt;script&gt;
    //字符串
        var text = '&lt;?php echo $text ?&gt;';
    console.dir(text);

        //数组
    var articlesJson = '&lt;?php echo json_encode($articles); ?&gt;';
    var articles = JSON.parse(articlesJson);
    console.dir(articles);
&lt;/script&gt;
</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' =&gt; '标题1',
                'content' =&gt; '内容1'
            ],
            [
                'title' =&gt; '标题2',
                'content' =&gt; '内容2'
            ]
      ];
      return view('test/test',$data);
    }
}
</code></pre>
<p><strong>js</strong></p>
<pre><code class="language-js">&lt;script&gt;
        //字符串
    var text = '{{$text}}';
    console.dir(text);

        //数组
    var articlesJson = '{!! json_encode($articles) !!}';
    var articles = JSON.parse(articlesJson);
    console.dir(articles);
&lt;/script&gt;
</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]
查看完整版本: js使用php变量