我需要从php数据中提取URL,我该如何实现?
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>
警报消息无法正常打印H T(我认为这些是http:// ...)
答案 0 :(得分:1)
您将返回一个未解析为JSON的字符串。
只需将dataType: "json"
添加到ajax设置即可。
由于你在javascript中将它作为数组读取,你应该像这样返回它:
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
答案 1 :(得分: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);
}
});