现在,我要做的是在页面上显示一些列表,并使用Jquery从服务器中提取该信息。代码如下:
<div class="list" name="category1" />
<div class="list" name="category2" />
<div class="list" name="category3" />
....
$(".list").ready(function(){
$.post("/getData", "{name=category#}"
function(data) {
// Do something here to display the list
}
);
});
假设/ getData返回所需的ul .... / ul html数据,如何用发回的数据替换div中的文本?我尝试了$ this.html(数据)的不同变体而没有运气。另外,有没有办法选择要作为.post参数发回的div的名称?
答案 0 :(得分:1)
对于初学者,您的代码中有一些错误。 ready事件应该用在文档对象上,而不是列表类。此外,您在$ .post调用中缺少逗号。这是已添加动态方面的更正代码。我没有对其进行测试,但它应该可以阻止可能需要进行的任何细微更改。
$(document).ready(function() {
$('.list').each(function() {
var list = $(this);
$.post('/getdata', {category: list.attr('name')}, function(result) {
list.html(result);
});
});
});
答案 1 :(得分:0)
尝试$(div[name=category1]).html(dataFromResponse);
或者,如果您想在每个div中使用相同的文字:$(div.list).html(dataFromResponse);
。这一切都取决于您的上下文,如果您没有任何其他匹配选择器,则可以跳过div
。
根据评论进行编辑:你的意思是这样吗?
// fetch new content
function getContentByCategory(name) {
$.post(
'/getData',
{category: name},
function(response) { handleResponse(name, response); }
);
}
// change the looks
function handleResponse(name, response) {
$('div[name='+name+']').html(response);
}
// trigger it all
$('.list').each(function(){
getContentByCategoryName($(this).attr('name'));
});