【发布时间】:2012-01-09 04:40:00
【问题描述】:
我的 JSON 检索数据有问题,请检查整个代码
这是我的 MySQL 表:
mysql> select imgurl from images where family="shoes";
+-------------------------------+
| imgurl |
+-------------------------------+
| images/zara/shoes/thumbnail |
| images/hermes/shoes/thumbnail |
| images/hermes/shoes/thumbnail |
| images/hermes/shoes/thumbnail |
+-------------------------------+
从上表中,我使用这个 jQuery 代码检索图像 url:
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
$('#sliderid, .prodcls').fadeOut(4000);
var txt = $(this).text();
$.ajax({
type: 'POST',
url: 'thegamer.php',
data: {send_txt: txt},
datatype:'json',
success: function(data){
$('#pgwrapid').html(data);
}
});
});
});
这是从 jQuery ajax 获取请求的 php 代码:
<?php
//Credentials
$server = "localhost";
$user = "root";
$db = "lemonx";
//Connect
$link = mysql_connect($server, $user);
//Select database
mysql_select_db($db, $link);
//Assemble query
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[$i] = $row['imgurl'];
//echo $imgurl[$i];
$i+=1;
}
}
echo json_encode($imgurl);
?>
现在,在下面的 jQuery 选择器中输出会发生什么:
$('#pgwrapid').html(data);
输出
["images\/zara\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail","images\/hermes\/shoes\/thumbnail"]
我的问题是:
- 为什么这里有反斜杠?
-
是否有任何代码可以循环上述输出并提取每个路径并将其插入图像标签中,如下所示:
$('#pgwrapid').append("<img src='"imagepath"' alt='Thumbnail'/>");
代码会很有用。
【问题讨论】:
-
不确定反斜杠是怎么回事,但就创建新的
<img>元素而言,如果data是一个数组,则使用for循环或jQuery 的@987654321 循环遍历它@ 一次处理一个数组的元素。 -
我用 alert(typeof(data));它给出了字符串
-
你有一堆问题已经得到解答,显然对你有所帮助,但你还没有accepted them。请做其他人可能不愿意帮助你的事情。
-
你试过在你的while循环中使用
strip_slashes($row['imgurl'])吗? -
@Sathya thanx 我标记了对我有帮助的答案