【问题标题】:PHP associative array solution to work with jQuery AJAX使用 jQuery AJAX 的 PHP 关联数组解决方案
【发布时间】: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("&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 中回显数据的特定格式,我可以做出来。我是初学者。

【问题讨论】:

  • 我很困惑。您是否质疑如何在 javascript 中创建关联数组?如果您不需要动态更改名称,则可以从 PHP 中输​​出名称。
  • 我希望它们动态改变.. :) ... 我需要一个 PHP 格式的解决方案和一个 javascript 来解码数据并按照我提到的那样使用它。问题是原型和原始语法不同..多数民众赞成y.. :)
  • 我想在第一个单元格下方的单元格中显示 name1,在第二个单元格中显示 name2,依此类推...但是应该从单个数组中检索数据..
  • 你试过用关联数组在 PHP 中的 json_encode 函数吗?
  • 提示:您可以像这样创建纯整数数组:$array = range(1, 19);

标签: php javascript json jquery


【解决方案1】:

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

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

Associative Array 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] 

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 2013-10-22
    • 2011-10-01
    • 2011-07-15
    • 2011-07-20
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多