将数据从php传递回ajax

时间:2012-06-09 11:07:50

标签: php javascript ajax jquery

如何将数据从当时行的php传回ajax?

PHP

$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);

while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {

$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];


}

echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);

的Ajax

$(".goButton").click(function() {
   var dir =  $(this).attr("id");
   var imId = $(".theImage").attr("id");

   $.ajax({
      url: "viewnew.php",
      dataType: "json",
      data: {
         current_image: imId,
         direction    : dir
      },
      success: function(ret){
          console.log(ret);
          var arr = ret;
          alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]);  // This code isnt working
          alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
          $(".theImage").attr("src", arr[0]);
          if ('prev' == dir) {
            imId ++;
         } else {
            imId --;
         }
         $("#theImage").attr("id", imId);
      }
   });

});
});
</script>

我的问题是如何在这里显示值?警告信息给我“未定义”?

3 个答案:

答案 0 :(得分:11)

你可以沿着这些方向做点什么。

PHP

$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);

$pictures = array();
while ($row = mysql_fetch_array($res)) {
  $picture = array(
    "pic_location" => $row['pic_location'],
    "name"         => $row['name'],
    "age"          => $row['age'],
    "gender"       => $row['gender']
  );
  $pictures[] = $picture;
}

echo json_encode($pictures);

JS

...
$.ajax({
  ...
  dataType: "json",
  ...
  success: function(pictures){
    $.each(pictures, function(idx, picture){
      // picture.pic_location
      // picture.name
      // picture.age
      // picture.gender
    });
  }
});
...

答案 1 :(得分:2)

您不能为AJAX响应添加多个echo语句:

echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);

加入您的阵列并发送一个响应:

$arr = $url + $name + $age + $gender;
echo json_encode($arr);

答案 2 :(得分:2)

您可以使用单个数组轻松完成此操作:

$pics = array();

while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $pics[$rec['id']]['url'] = $rec['pic_location'];
  $pics[$rec['id']]['name']=$rec['name'];
  $pics[$rec['id']]['age']=$rec['age'];
  $pics[$rec['id']]['gender']=$rec['gender'];
}

echo json_encode($pics);