我的脚本如下
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
success : function(response) {
$.each(response, function(index, value) {
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
});
$('.tree').append( response.join('') );
},
error : function(res, textStatus) {
var msg = "Unable to load Subfolder";
alert(msg);
}
});
setStatus($(this));
});
});
在这里,我想将数据表示 id
与某些响应元素进行比较,例如
success : function(response) {
$.each(response, function(index, value) {
if(id==value.rootId){
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
response.push('<li class="tree-title" ></li>');
alert("Append Failed");
}
});
$('.tree').append( response.join('') );
},
但它不起作用
我怎样才能实现这个目标?有人可以建议我吗?
最佳答案
您可以为成功回调提供属性,并使用 this
从闭包中访问它们。示例 this.id
您指定的自定义属性不能在 ajax
原型(prototype)中定义,否则您将重写默认值。试试这个:
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
id : id,
success : function(response) {
afterSuccess(response , this.id);
function afterSuccess(data, i) {
$.each(data, function(index, value) {
if(i==value.rootId){
data.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
alert("Append Failed");
}
});
$('.tree').append( data.join('') );
}
}
});
setStatus($(this));
});
});
关于javascript - 使用 jquery 将数据与 ajax 响应进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626742/