使用jQuery ajax响应数据 [英] Using jQuery ajax response data
问题描述
我正在使用ajax发布,并且正在接收html形式的数据.我需要拆分数据并将数据片段放置在整个页面上.我将响应数据构建为类似于<p id='greeting'> Hello there and Welcome </p> <p id='something'>First timer visiting our site eh'</p>
的格式,虽然有点复杂和动态,但如果可以解决此问题,我可以弄清楚.谢谢
I am using ajax post and am receiving data in the form of html. I need to split up the data and place pieces of the data all over the page. I built my response data to be something like <p id='greeting'> Hello there and Welcome </p> <p id='something'>First timer visiting our site eh'</p>
It is a little more complicated and dynamic but I can figure it out if get this question answered. Thanks
$.ajax({
type:'POST',
url: 'confirm.php',
data: "really=yes&sure=yes",
success:function(data){
//Need to split data here
}
});
推荐答案
更新:刚意识到您应该这样做:
Update: Just realized you should probably do this:
success:function(data) {
data = $('<div/>').append(data);
$('#greeting',data).appendTo('#one')
$('#something',data).appendTo('#two')
}
由于.find
不是孩子,所以不能正确使用它,但是如果将它附加到一个空节点上,则可以.另一种选择是使用.filter
As you cant use .find
properly since it isnt a child but if you append it to an empty node you can. The other alternative would be using .filter
$.ajax({
type:'POST',
url: 'confirm.php',
data: "really=yes&sure=yes",
success:function(data){
$('#greeting',data).appendTo('#one')
$('#something',data).appendTo('#two')
}
});
您可以从data
中提取并追加到想要的位置.您还可以执行类似返回JSON的操作,而不是从html提取html,而只是从对象访问html.
You can extract from data
and append where you want to. You can also do something like return JSON instead, and instead of extracting html from html just access the html from an object.
$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')
响应必须是:
({ 'greeting':'html', 'something' :'other html' })
这篇关于使用jQuery ajax响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!