【发布时间】:2012-02-15 03:00:50
【问题描述】:
我看到了很多相关的例子,但我仍然感到困惑。我正在使用 ajax(我不太了解)来获取每 xxx 秒更新一次文件的结果。如果我只传递一个变量,它工作得很好,但是如果我需要从 php 传递一个数组,最好的方法是什么?
结构很简单:
show_results.php
<?php
include_once('modWhosonlineCustom.inc.php');
$document->addScript("http://code.jquery.com/jquery-latest.js");
$document->addScript("ajax.js");
$array_name = modWhosonlineCustom::getOnlineUserNames();//the array I need to pass to javascript variable
?>
<script>
var whosonline = '<?php echo "$array_name"; ?>';
</script>
<div id="results"></div>
Ajax 代码比在 url 加载中构建多个参数:
ajax.js
$(document).ready(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]");
var refreshId = setInterval(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
回到 PHP 响应页面,如何再次使用通过 url 传递的数组参数?
response.php
<?php
$names = $_GET['array_name'];
foreach ($names as $name) {
//do something
非常感谢任何建议,谢谢!
编辑
谢谢大家,我认为我现在是正确的方法,但问题是通过 javascript 中的 url 传递这个数组。或者我在 php 结束回调文件中没有以正确的方式得到它。我会告诉你修改了什么:
show_results.php
...
<?php
$names = modWhosonlineCustom::getOnlineUserNames();
?>
<script>
var whosonline = '<?php echo "json_encode($names)"; ?>';
</script>
ajax.js
$(document).ready(function() {
$("#atendentes").load("response.php?names=" + whosonline);
var refreshId = setInterval(function() {
$("#atendentes").load("response.php?names=" + whosonline + "&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
response.php
$users = $_GET['names'];
$users = json_decode($users);
echo "user: $users";
$names = $users;
foreach ($names as $name) {
...
在另一边我得到:警告:在第 33 行的 response.php 中为 foreach() 提供的参数无效,并且回显为空
缺少什么?
【问题讨论】:
标签: php ajax arrays url joomla