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

标签 php javascript json jquery

我有如下的 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/

相关文章:

php - 关于 JavaScript 和安全性

c# - 在 C# 中使用 Newtonsoft Json.NET 反序列化 JSON

json - 将复杂的 JSON 解析为 goweb REST Create() 函数

php - 在 Joomla 管理员中使用 JRoute::_()

javascript - 将数组转换为具有预定义键的映射

php - 从记录中读取随机行 MySQL-PHP

javascript - 单击后关闭悬停事件并保持单击

python - 使用 json 和 python 序列化/反序列化对象列表

php - 无法使用 Facebook 登录从我的网站注销。?

PHP序列化字符串格式