我正在使用ajax post并接收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
}
});
最佳答案
更新:刚刚意识到你可能应该这样做:
success:function(data) {
data = $('<div/>').append(data);
$('#greeting',data).appendTo('#one')
$('#something',data).appendTo('#two')
}
因为您无法正确使用 .find
因为它不是子节点,但如果您将其附加到空节点,则可以。另一种选择是使用 .filter
$.ajax({
type:'POST',
url: 'confirm.php',
data: "really=yes&sure=yes",
success:function(data){
$('#greeting',data).appendTo('#one')
$('#something',data).appendTo('#two')
}
});
您可以从数据
中提取数据并将其附加到您想要的位置。您还可以执行类似 return JSON 之类的操作,而不是从 html 中提取 html,只需从对象访问 html。
$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')
响应必须类似于:
({ 'greeting':'html', 'something' :'other html' })
关于jquery - 使用 jQuery ajax 响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031062/