简体   繁体   English

从ajax响应中提取数据

[英]Extracting data from a ajax response

I need to extract the URL's from the php datas, how can i achieve this? 我需要从php数据中提取URL,我该如何实现?

PHP PHP

$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);


while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url.=$rec['pic_location'].";";
}

echo json_encode($url);

Ajax 阿贾克斯

 <script type="text/javascript">
    $(document).ready(function() {
    $(".goButton").click(function() {
       var dir =  $(this).attr("id");

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

    });
    });
    </script>

the alert message isn't working its just printing HT ( i think these are http://... ) 警报消息无法正常打印HT(我认为这些是http:// ......)

You're returning a string which is not parsed as JSON. 您将返回一个未解析为JSON的字符串。 Just add dataType: "json" to the ajax settings. 只需将dataType: "json"添加到ajax设置即可。

And since you're reading it as an array in your javascript you should return it like so: 因为你在javascript中将它作为一个数组读取,你应该像这样返回它:

while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url[] = $rec['pic_location'];
}

You are sending a string in your PHP and expecting an array as response in javascript. 您正在PHP中发送一个字符串,并希望在javascript中将数组作为响应。 Change you PHP to 把PHP改成

while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url[] = $rec['pic_location'];
}

And javascript to 和javascript到

$.ajax({
      url: "viewnew.php",
      dataType: "JSON",
      data: {
         current_image: imId,
         direction    : dir
      },
      success: function(ret){
          console.log(ret[0]);
          var arr = ret;
          alert(arr);  
          alert("first: " + arr[0] + ", second: " + arr[1]);    // THIS IS NOT WORKING!!!!
          if ('prev' == dir) {
            imId ++;
         } else {
            imId --;
         }
         $("#theImage").attr("id", imId);
      }
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM