gpt4 book ai didi

与 jQuery AJAX 一起工作的 PHP 关联数组解决方案

转载 作者:可可西里 更新时间:2023-11-01 00:36:29 24 4
gpt4 key购买 nike

我有如下的 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("&nbsp;");
}
});
},
});
});
</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" >&nbsp;</td>
<td class="content" >&nbsp;</td>
<td class="content" >&nbsp;</td>
<td class="content" >&nbsp;</td>
<td class="content" >&nbsp;</td>
<td class="content" >&nbsp;</td>
<td id="next">next</td>
</tr>
<tr>
<td>&nbsp;</td>
<td class="title" >&nbsp;</td>
<td class="title" >&nbsp;</td>
<td class="title" >&nbsp;</td>
<td class="title" >&nbsp;</td>
<td class="title" >&nbsp;</td>
<td class="title" >&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>

一切正常。

但我想显示一些数据,与数组中的数字相关,说一些名称,name1name20 相对于数组元素。在我的页面中,具有 class="title" 的表格单元格填充了数组元素(这里是图像名称)。但我想要 class="title" 填充名称 1-20,这些名称应该与数组元素(如关联数组)一起传递。我认为关联数组将是最佳选择。

我如何使用 JavaScript 和 jQuery 做到这一点?

注意:不用担心 PHP。如果有人建议用 PHP 回显数据的特定格式,我可以弄清楚。我是初学者。

最佳答案

一个关联数组会变成一个带有json_encode的javascript对象

普通数组如array(1,2,3) ==json_encode ==> [1,2,3]

关联数组 like array( 'name' => 1, 'name2' => 2 ) ==json_encode ==> { name :1 , name2: 2}

因此 result[index] 将不再起作用。

最好的方法是发送一个包含两个数组的对象:

PHP:

array( 'classes' => array('name1','name2') , 'ids' => array(1,2));

在 Javascript 中你可以像这样访问它:

result.classes[index]
result.ids[index]

关于与 jQuery AJAX 一起工作的 PHP 关联数组解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6403945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com