我从这里得到了以下代码,同时在一个单独的.js
文件中搜索从YUI2 JavaScript函数访问PHP变量的某种方式。
namespace
,第二个语句开始定义一个函数(命名为YAHOO.MyApp)。然后var currencyRates;
和var userInfo;
创建两个变量。那么下一个
return {...}
结构是什么?里面是
function(newRates) { currencyRates = newRates; }
看起来像一个函数(特别是因为PHP可能会调用它)传递给它数组$currency rates
?但总的来说initCurrencyRates: function(newRates) { currencyRates = newRates; }
?什么是
:
那里(就像=
是分配)?那么最后的
();
呢?是什么something=function(){...}();
结构?
YAHOO.namespace('MyApp');
YAHOO.MyApp = function() {
var currencyRates;
var userInfo;
/*
here a lot of code with event listeners and dom manipulations which uses currencyRates and userInfo variables
*/
return {
initCurrencyRates: function(newRates) { currencyRates = newRates; },
initUserInfo: function(newUserInfo) { userInfo = newUserInfo; },
}
}();
PHP: <?php
$currencyRates = array('EUR' : 1.3245, 'GBP': 1.4322, 'RUB': 0.02334); //actually it comes from database
print '<script>YAHOO.MyApp.initCurrencyRates(' . json_encode($currencyRates) . ')</script>';
$userInfo = array('Name' => 'Jhon', 'ID' => 10); //actually it comes from database
print '<script>YAHOO.MyApp.initUserInfo(' . json_encode($userInfo) . ')</script>';
?>
您正在查看Javascript对象字面量。它们有点类似于PHP的散列文字。下面的Javascript代码
var foo = {
x: "hello",
y: "world"
}
和下面的PHP代码有点类似:
$foo = array(
"x" => "Hello",
"y" => "World"
)