开发者

PHP associative array solution to work with jQuery AJAX

I have JavaScript as below;

<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{
        开发者_JAVA技巧$(this).html("&nbsp;");
      }
    });
  },
  });
});
</script>

Which, with the help of my php file;

<?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);
?>

changes background image of my table;

<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>

And everything works well.

But I want to display some data, related with the numbers in array, say some names, name1 to name20 with respect to array elements. In my page, the table cells having class="title" get populated with array elements (here image names). But I want class="title" filled with names 1-20, which should be delivered along with array elements like an associative array. I think associative array will be the best option.

How can I do this using JavaScript and jQuery?

Note: don't worry about PHP. If somebody suggest a specific format to echo data in PHP, I can make it out. I am a beginner.


An associative array will become an javascript object with json_encode

Normal array like array(1,2,3) ==json_encode ==> [1,2,3]

Associative Array like array( 'name' => 1, 'name2' => 2 ) ==json_encode ==> { name :1 , name2: 2}

So result[index] will not work anymore.

The best way is to send an Object with two Arrays in it :

PHP:

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

In Javascript you can access it like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜