簡體   English   中英

Yii:將數據從php傳遞到JS的最佳做法

[英]Yii: best practices to pass data from php to JS

我的問題是,將數據從服務器端傳遞到客戶端的最佳實踐是什么?

例如,我在服務器端有一個cartId ,我需要將其傳遞給客戶端。

我最好怎么做? 現在,它是通過主布局完成的:

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

但是,這似乎是一件壞事。 將不勝感激任何反饋。

在php文件中編寫此YII代碼

YII代碼

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

腳本

(function() {
if (window.cart) {
    cart.id = cartid;
}
})();
  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。

最好不要在JavaScript中編寫PHP。 取而代之的是,從PHP中獲取數據並將其傳遞給json_encode( http://php.net/json_encode )並將其回顯。 如果願意,可以直接將其讀取為變量,但是使用ajax更好,因為它是異步的,因此可以更好地加載頁面。

最好的選擇是對執行某些操作並返回數據的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); 
});

如果您只是想防止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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM