使用jQuery ajax响应数据

The*_*ile 10 jquery

我正在使用ajax帖子并以html的形式接收数据.我需要分割数据并在整个页面上放置数据.我建立了我的响应数据,<p id='greeting'> Hello there and Welcome </p> <p id='something'>First timer visiting our site eh'</p>它有点复杂和动态,但如果得到这个问题,我可以弄明白.谢谢

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    //Need to split data here
            }
        });
Run Code Online (Sandbox Code Playgroud)

med*_*iev 6

更新:刚刚意识到你应该这样做:

success:function(data) {
    data = $('<div/>').append(data);
    $('#greeting',data).appendTo('#one')
    $('#something',data).appendTo('#two')
}
Run Code Online (Sandbox Code Playgroud)

因为你不能.find正确使用它,但是如果你将它附加到一个空节点你可以.另一种选择是使用.filter

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    $('#greeting',data).appendTo('#one')
                    $('#something',data).appendTo('#two')
            }
        });
Run Code Online (Sandbox Code Playgroud)

您可以从中提取data并追加到您想要的位置.您也可以执行类似返回JSON的操作,而不是从html中提取html,只需从对象访问html即可.

$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')
Run Code Online (Sandbox Code Playgroud)

回应必须如下:

({ 'greeting':'html', 'something' :'other html' })
Run Code Online (Sandbox Code Playgroud)