简体   繁体   English

对promise.done返回的数据使用jquery.each时出错

[英]error using jquery.each on data returned by promise.done

I am new with Promises. 我对Promises陌生。 This is also my first post on stackoverflow. 这也是我关于stackoverflow的第一篇文章。 I am trying to refactor the following procedure using promises: 我正在尝试使用promise重构以下过程:

var listBuilder = (function() {

$.post("sc.php",{task: "getLocations"},function(data) {
    $.each(data, function(i,item) {
        $('<li>',{id: "loc-" + item.idlocatii, text: item.denumire})
            .appendTo("#lista")
            .addClass("locationList")
            .draggable({
                revert: "invalid",
                helper: "clone"
            });
    });
},'json');

})();

So I came with the following code to replace the above: 因此,我提供了以下代码来替换上面的代码:

var listBuilder = (function() {

function addListItem(item) {
    $('<li>',{id: "loc-" + item.idlocatii, text: item.denumire})
        .appendTo("#lista")
        .addClass("locationList")
        .draggable({
            revert: "invalid",
            helper: "clone"
        });
}

var getLocations = $.post("sc.php",{task: "getLocations"},'json');

getLocations.done(function(data) {
    $.each(data, function(i,item) {
        addListItem(item);
    });
});

})();

The refactored version of code returns the error below: 代码的重构版本返回以下错误:

Uncaught TypeError: Cannot use 'in' operator to search for '1026' in [{"idlocatii":"1","denumire":"Hirsch Hopfen"},{"idlocatii":"2","denumire":"Berlinerstr. 24"},{"idlocatii":"3","denumire":"Pfalzerstr. 26"},{"idlocatii":"4","denumire":"Christophal......}] Uncaught TypeError:无法使用'in'运算符在[{{“ idlocatii”:“ 1”,“ denumire”:“ Hirsch Hopfen”},{“ idlocatii”:“ 2”,“ denumire”:“中搜索'1026' Berlinerstr。24“},{” idlocatii“:” 3“,” denumire“:” Pfalzerstr。26“},{” idlocatii“:” 4“,” denumire“:” Christophal ......}

Can you explain where is the error? 您能解释错误在哪里吗?

Thank you! 谢谢!

It's possible that the data you're getting back is actually a JSON string and not an object. 您返回的数据实际上可能是JSON字符串而不是对象。 What happens if you change your getLocations.done block to the following: 如果将getLocations.done块更改为以下内容,会发生什么:

getLocations.done(function(data) {
    var parsedData = JSON.parse(data);
    $.each(parsedData, function(i,item) {
        addListItem(item);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM