2012-06-08 158 views
0

我需要从php数据中提取URL,我该如何实现?从ajax响应中提取数据

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

阿贾克斯

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

警报消息不工作它只是打印HT(我觉得这些都是HTTP:// ...)

+0

什么的的console.log节目吗? –

+0

@FlorianMargaine - 无法加载资源:服务器以$(“。theImage”)。attr(“src”,+ arr [0]);“'和' alert(arr [0]);'显示正确的URL – Yahoo

回答

1

你”重新返回一个未被解析为JSON的字符串。 只需将dataType: "json"添加到ajax设置即可。

而且因为你读它在你的JavaScript数组,你应该像这样返回它:

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

谢谢,我现在正在提醒框中收到一条有效的消息:)但为什么图像的Scr不会改变? '警报(ARR [0]); (“。theImage”)。attr(“src”,+ arr [0]);'检查元素显示Src = NaN – Yahoo

+1

删除+因为你不想计算任何东西。 JS现在假设你的意思是0 + arr [0] – Thomas

1

你发送你的PHP的字符串,并期待一个数组在JavaScript响应。改变你的PHP

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

和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); 
     } 
    }); 
+0

谢谢,我现在正在提醒框中收到一条有效的消息:)但为什么不是图像更改的Scr? '警报(ARR [0]); (“。theImage”)。attr(“src”,+ arr [0]);'检查元素显示Src = NaN – Yahoo

+1

不使用'+ arr [0]'并且还放置了一个警报(arr [0])'看看你真的把'src'属性设置为 – slash197