数据传递回从PHP阿贾克斯 [英] Passing data back from php to ajax

查看:108
本文介绍了数据传递回从PHP阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以传递数据的再PHP行回AJAX?

How can I pass data from a php of then rows back to 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);

阿贾克斯

$(".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>

我的问题是我怎么可以在这里显示的数值?该提示信息给我未定义?

My question is how can I display the values here ? The Alert message is giving me "Undefined" ?

推荐答案

您可以做这些方针的东西。

You can do something along these lines.

$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
    });
  }
});
...

这篇关于数据传递回从PHP阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆