为什么这个函数不修改数组的全局版本?
Why doesn't this function modify the global version of the array?
我定义了一个我认为是全局作用域的变量。我想在类中的函数中修改相同的变量,然后稍后使用它作为json数据导出。
函数是由xataface api调用的,所以我不确定我是否可以通过函数签名来做一些像引用传递这样的事情。我想我可能会访问这个动作类的实例在javascript中嵌入php,但我不知道如何向api请求它,我也不相信它的生命周期。全局变量似乎是可行的方法。无论如何,我想知道:
- 为什么不是$dataset1的全局实例在函数内被修改?
- 为什么调用array_push不把任何东西放在数组上?
<?php //non-dynamic data delcared in global scope. This is picked up later //in a php block embedded into javascript $dataset1 = array(array("label"=>"c120","data"=>"1"), array("label"=>"c150","data"=>"10"), array("label"=>"camp","data"=>"7")); class actions_time_in_type { function handle(&$params) { $this->app =& Dataface_Application::getInstance(); //The Query $result = mysql_query("SELECT typeDes, total FROM myTable", $this->app->db()); //reserch leads me to believe that this *should* make all subsequent //references to $dataset1 use the global instance global $dataset1; //experimenting with appending more non-dynamic data //for some reason, this syntax does not seem to touch $dataset1 array_push($dataset1, array("label"=>"dv20","data"=>"1")); //This syntax is working, but $dataset1 is not the same as the global //$dataset1. Prepending "global" here seems to crash the script $dataset1[] = array("label"=>"pa18","data"=>"5"); while($row = mysql_fetch_assoc($result)) { //append data to the array, again, this is not hitting //the global instance of $dataset1 $dataset1[] = array("label"=>$row['typedes'],"data"=>$row['total']); } mysql_free_result($result); //Frees the result after finished using it //diagnostic dump to see what we've got //This shows that we've constructed the dynamic data set, but it //seems to be scoped only to this function and does not make it into //javascript. var_dump($dataset1); } } ?> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script> <script type="text/javascript"> $(function () { //This is getting only what was done original init of $dataset1, nothing that //happened in the function made a difference var dataset1 = <?php echo json_encode($dataset1); ?>; }); </script>
看来这确实是执行顺序的问题。由于数据的操作发生在类定义中,而类定义又由api调用,因此似乎无法保证当操作数据时数据的全局定义将在范围内,或者当数据被进一步重用时它将被操作。
对于感兴趣的读者,我能够让api开发人员演示调用类内函数将javascript与api集成的正确方法:
https://groups.google.com/forum/!主题/xataface l6qBzxF1vrc
相关文章:
- 全局变量和全局对象的属性之间有什么区别吗
- 正在全局范围中查找JavaScript函数
- delete关键字在全局变量上的不同行为
- 在javascript函数中设置全局变量
- 如何将getJson的响应保存在全局变量中
- JS编译器/包管理器,用于版本控制
- jQuery-2.1.1.min.js或最新版本jQuery-2.13.min.js不会't支持'@
- 全局对象是属于哪个类的对象
- Chrome加载旧版本的Javascript文件
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- Javascript全局onclick监听器
- 从Javascript方法返回全局变量
- 为什么jQuery 1.8不能在IE8和InternetExplorer9中使用?(截至2012年9月的IE9最新版本)
- 访问jsrender模板中的全局javascript变量并更新它
- 如何设置jsfiddle's的javascript版本
- javascript无法重新定义函数内部的全局对象
- 在JavaScript中定义全局对象的独立于实现的版本
- 站点在本地工作/不在Openshift上工作(与服务器、全局npm包版本同步本地、全局npm包版本)
- 为什么我的全局变量在我的javascript文件的缩小版本中是未定义的?
- 为什么这个函数不修改数组的全局版本?