[英]What are some best practices for transporting data from PHP to Javascript?
[英]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;
}
})();
使用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.