【发布时间】:2011-06-19 17:25:35
【问题描述】:
我有如下的 JavaScript;
<script type="text/javascript">
$(document).ready( function() {
var i = 1;
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=' + i,
dataType: 'json',
cache: false,
success: function(result) {
$('.content').each(function(index){
if((result[index])){
$(this).css({ 'background-image':'url(images/' + result[index] + '.jpg)' });
}else{
$(this).css({ 'background-image':'url()' });
}
});
$('.title').each(function(index){
if((result[index])){
$(this).html(result[index]);
}else{
$(this).html(" ");
}
});
},
});
});
</script>
其中,借助我的 php 文件;
<?php
$id = $_POST["id"];
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$quantity = 6;
$offset = ($id-1)*$quantity;
$array2 = array_slice($array,$offset,$quantity);
echo json_encode($array2);
?>
改变我的桌子的背景图片;
<table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0">
<tr>
<td id="prev">prev</td>
<td class="content" > </td>
<td class="content" > </td>
<td class="content" > </td>
<td class="content" > </td>
<td class="content" > </td>
<td class="content" > </td>
<td id="next">next</td>
</tr>
<tr>
<td> </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td> </td>
</tr>
</table>
一切正常。
但我想显示一些与数组中的数字相关的数据,比如一些名称,name1 到 name20 与数组元素有关。在我的页面中,具有class="title" 的表格单元格填充有数组元素(此处为图像名称)。但我希望 class="title" 填充名称 1-20,它应该与关联数组等数组元素一起提供。我认为关联数组将是最好的选择。
如何使用 JavaScript 和 jQuery 做到这一点?
注意:不要担心 PHP。如果有人建议在 PHP 中回显数据的特定格式,我可以做出来。我是初学者。
【问题讨论】:
-
我很困惑。您是否质疑如何在 javascript 中创建关联数组?如果您不需要动态更改名称,则可以从 PHP 中输出名称。
-
我希望它们动态改变.. :) ... 我需要一个 PHP 格式的解决方案和一个 javascript 来解码数据并按照我提到的那样使用它。问题是原型和原始语法不同..多数民众赞成y.. :)
-
我想在第一个单元格下方的单元格中显示 name1,在第二个单元格中显示 name2,依此类推...但是应该从单个数组中检索数据..
-
你试过用关联数组在 PHP 中的 json_encode 函数吗?
-
提示:您可以像这样创建纯整数数组:
$array = range(1, 19);
标签: php javascript json jquery