jquery将数组转换为字符串html


jquery convert array to string html

如标题所述。我该怎么做?我在一些论坛上读到使用字符串以及如何使用它?

PHP:

$notes = $db->query("SELECT * FROM notes WHERE id_user = '$id_user'");
$output = array();
while($note = $notes->fetch_assoc()) {
  $noting = '<span class="block_note">'.$note['note'].'</span>';
  array_push($output, $noting);
}
$data['ok'] = true;
$data['message'] = $output;
echo json_encode($data);

jQuery:

$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data, function(key,id){
        $("#notes").append(data.message);
     })
  }
}, "json");

输出:

{
"ok":true,
"message":[
  "<span class='"block_note'">note1<'/span>",
  "<span class='"block_note'">note2<'/span>",
  "<span class='"block_note'">note3<'/span>"
]
}
$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data.message, function(key,value){
        $("#notes").append(value);
     })
  }
}, "json");

array.join(分隔符(

在您的情况下:

message = data.message;
html = message.join('');

我认为最简单的方法是使用jQuery.toArray((函数,然后使用javascript join((。

像这样:

var myArray = $(".block_note").toArray();
myArray.join("");
$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data.message, function(key,id){
     $("#notes").append(id);
    });
  }
}, "json");

看看这里的小提琴http://jsfiddle.net/ryan_s/58cLY/

data.message是一个JavaScript Array,因此您可以使用Array.join方法:

...
if (data.ok){
    $("#notes").append(data.message.join(""));
}
...

Array对象还提供了各种迭代方法,您会发现这些方法很有用。

附言:你也可以这样写你的PHP代码:

$data = array();
$data['message'] = array();
while($note = $notes->fetch_assoc()) {
    $data['message'][] = '<span class="block_note">' . $note['note'] . '</span>';
}
$data['ok'] = true;