2012-12-01 148 views
1
<suggestions> 
<user> 
<![CDATA[ Chris ]]> 
</user> 
<user> 
<![CDATA[ Christina ]]> 
</user> 
</suggestions> 

和JS部分jQuery的AJAX請求返回XML

  $.ajax({ 
       type: "POST", 
       url: 'index.php/Suggest/', 
       dataType: 'xml', 
       data: {username: username}, 
       success: function(data) { 
        $(data).find('suggestions').each(function(){ 
         if ($(this).find('user').text()) { 
          $('#container').html('<div>' + $(this).find('user').text() + '</div>'); 
         } 
        }); 
       }, 
       error: function(request, status, error) { 
        // will also occur when the user toggles a window and instantly clicks on a link, so don't alert anything 
       } 
      }); 

插入

<div>ChrisChristina</div> 

,但我想

<div>Chris</div> <div>Christina</div> 

回答

1

您應該使用append而不是html如果你要添加的所有用戶:

$(data).find('suggestions').each(function(){ 
     $(this).find('user').each(function(){ 
      $('#container').append('<div>' + $(this).text() + '</div>'); 
     }); 
    }); 
+0

'成功:功能(數據){ \t \t \t \t \t \t $( '#cChatMenuContentContainer')空(); \t \t \t \t \t \t $(數據).find( '用戶')每個(函數(){ \t \t \t \t \t \t \t $( '#cChatMenuContentContainer')附加( '

' + $(this).text() + '
');。。 \t \t \t \t \t \t}); \t \t \t \t \t},'對我有用,thx – Chris

1

我認爲它遍歷的suggestions。相反,它應該重複執行user。這裏是工作代碼:

var response = ""+ 
"<suggestions>" + 
"<user>" + 
"<![CDATA[ Chris ]]>" + 
"</user>" + 
"<user>" + 
"<![CDATA[ Christina ]]>" + 
"</user>" + 
"</suggestions>"; 

// This is using the JSFiddle "echo" interface 
$.post("/echo/xml/", {"xml": response}, function(data) { 
    $(data).find('user').each(function(i, user){ 
     $("#container").append($("<div>").text($(user).text())); 
    }); 
});​ 

您可以查看它live on JSFiddle

0

您需要遍歷每個user元素。在多個元素上使用text()方法時,將返回所有文本,但方法無法識別以添加空格。

$(data).find('suggestions').each(function() { 
    var $user=$(this).find('user'); 
     /* use length to check if user elements exist*/ 
    if($user.length){ 
      var user=$user.map(function(){ 
      return $(this).text(); 
      }).get().join(' ') 

     $('#container').append('<div>' + user + '</div>'); 
    } 
});