0

下面是我的 AJAX 代码。我已经在评论中写了问题。

$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
success: function(arrayphp) {
     //here one by one text is being received from php  from within a loop
     //each text item is getting displayed as link here
     //it is OK that text is getting displayed as link
     //BUT the problem is that all the text returned from php are getting displayed as 
     //one link i.e between one "<a></a>"
     //I WANT THAT EACH TEXT SHOULD BE DISPLAYED AS SEPERATE LINKS
     //AS EACH TEXT IS GETTING RETURNED FROM WITHIN SEPARATE ITERATIONS OF PHP LOOP
     var link = $('<a href="#" class="album"><font color="red">' + arrayphp + '</font></a>');
    linkclass = link.attr("class"); 
    $(".searchby .searchlist").append(link);   
}
}); 

该怎么办?

4

1 回答 1

0

php 一次将所有内容都扔给 ajax 成功函数......您需要在 php 数组上使用 json_encode 并回显它以将其作为 json 数组传递。

<?php 
$return = array();
foreach($array as $key=>$value){
 //Do your processing of $value here
 $processed_value = $value;
 array_push($return, $processed_value);
}
echo json_encode($return);
?>

在 ajax 调用中,将 dataType 设置为“json”,以便它将从 php 传递的数据解析为 json 数组。遍历使用 jquery each 接收到的数组。

$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
dataType: "json",
success: function(arrayjson) {
     $.each(function(arrayjson, function(i, processed_value) {
       var link = $('<a href="#" class="album"><font color="red">' + processed_value + '</font></a>');
       linkclass = link.attr("class"); 
       $(".searchby .searchlist").append(link); 
    });  
}
}); 
于 2013-08-27T19:40:45.323 回答