【问题标题】:Yii: best practices to pass data from php to JSYii:将数据从 php 传递到 JS 的最佳实践
【发布时间】:2015-03-22 02:56:48
【问题描述】:

我的问题是,将数据从服务器端传递到客户端的最佳做法是什么?

例如,我的服务器端有一个cartId,我需要将它传递给客户端。

我怎样才能最好地做到这一点?现在它是通过主布局完成的:

<script type='text/javascript'>
    (function() {
         if (window.cart) {
             cart.id = <?php echo Yii::app()->getUser()->getCartId() ?>;
         }
    })();
</script>

但是,这似乎是一件坏事。如有任何反馈,我们将不胜感激。

【问题讨论】:

    标签: javascript php jquery yii


    【解决方案1】:

    在 php 文件中写下这个 YII 代码

    YII 代码

    Yii::app()->clientScript->registerScript("cartid",Yii::app()->getUser()->getCartId());
    

    脚本

    (function() {
    if (window.cart) {
        cart.id = cartid;
    }
    })();
    

    【讨论】:

      【解决方案2】:
      1. 使用 AJAX 从服务器获取您需要的数据。
      2. 将数据回显到页面某处,并使用 JavaScript 获取 来自 DOM 的信息。
      3. 将数据直接回显到 JavaScript。

      使用 AJAX,您需要两个页面,一个是 PHP 生成输出的地方,第二个是 JavaScript 获取该输出的地方:

      get-data.php
      
      /* Do some operation here, like talk to the database, the file-session
       * The world beyond, limbo, the city of shimmers, and Canada.
       * 
       * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
       * It all depends on the Content-type header that you send with your AJAX
       * request. */
      
      echo json_encode(42); //In the end, you need to echo the result. 
                            //All data should be json_encoded.
      index.php (or whatever the actual page is named like)
      
      <script>
          function reqListener () {
            console.log(this.responseText);
          }
      
          var oReq = new XMLHttpRequest(); //New request object
          oReq.onload = function() {
              //This is where you handle what to do with the response.
              //The actual data is found on this.responseText
              alert(this.responseText); //Will alert: 42
          };
          oReq.open("get", "get-data.php", true);
          //                               ^ Don't block the rest of the execution.
          //                                 Don't wait until the request finishes to 
          //                                 continue.
          oReq.send();
      </script>
      

      上述两个文件的组合会在文件加载完成时提示 42。

      【讨论】:

        【解决方案3】:

        最好不要在 JavaScript 中编写 PHP。相反,从 PHP 获取数据并将其传递给 json_encode (http://php.net/json_encode) 并回显。如果愿意,您可以将其直接读入变量,但最好使用 ajax,这样它是异步的,因此页面加载效果更好。

        【讨论】:

          【解决方案4】:

          最好的选择是对执行某些操作并返回数据的 PHP 页面进行 AJAX 调用。一旦 PHP 获得了它需要返回的所有数据,我就会以 JSON 格式回显数据(作为数组)。 例如:

          info.php

          die (
          json_encode(
              array(
                  "id" => "27"
                  "name" => "rogin",
          
              )
          )
          

          );

          然后,您可以使用 javascript 将数据提取到 json 对象中。

          JS

          $.getJSON(
          'info.php?',   
          function(jsonObject) { 
              alert(jsonObject.name); 
          });
          

          【讨论】:

            【解决方案5】:

            如果你只是想防止 javascript 语法高亮错误,引用就可以了。

            (function() {
                 var the_id = +'<?php echo Yii::app()->getUser()->getCartId() ?>';
                 //           ^ + to convert back to integer
                 if (window.cart) {
                     cart.id = the_id;
                 }
            })();
            

            或者,如果您愿意,可以将其添加到元素中:

            <div id='foo' style='display:none'><?php echo Yii::app()->getUser()->getCartId() ?></div>
            

            以后再解析

            <script>
              (function() {
                 var the_id = +($('#foo').html()); // or parseInt
                                                   // or JSON.parse if its a JSON
                 if (window.cart) {
                     cart.id = the_id;
                 }
              })();
            </script>
            

            【讨论】:

              猜你喜欢
              • 2016-12-27
              • 2010-11-14
              • 2018-12-24
              • 1970-01-01
              • 1970-01-01
              • 2023-03-31
              • 2014-02-21
              • 1970-01-01
              • 2014-12-30
              相关资源
              最近更新 更多