迭代ul的所有项,并使用ajax调用将其插入数据库

Iterate all item of ul and insert into database using ajax call

本文关键字:调用 ajax 数据库 插入 ul 迭代      更新时间:2023-09-26

我是jquery新手。我想插入ul的所有列表项。我尝试了以下,但它不工作,请有人指导我代码有什么问题,因为我做了"async:false"但它仍然不工作

$('#sortable li').each(function () {  
            items += $(this).text();
            insertCustomBCFields($(this).text(), plu);
        });

和insertCustomBCFields ftn在

下面
function insertCustomBCFields(field, plu) {
        alert(field + plu);
        $.ajax({
            type: "POST",
            url: 'ProductDefinition.aspx/insertBCCustomFields',
            data: "{'field':'" + field + "', 'plu':'" + plu + "'}",
            contentType: "application/json; charset=utf-8",
            async: false,
            dataType: "json",
            success: function (data) {
                alert("Success");
            },
            failure: function (response) {
                alert("Insert Failed!");
            }
        });
    }

使用async: false,进行ajax调用将使其成为同步调用。此选项应设置为true,以进行异步调用async: false,,除非需要进行同步调用。

我可以看到,你每次调用ajax函数的li被发现在你的DOM结构(现在这是非常糟糕的性能方面),好吧,那不是那么好,相反,你可以使ajax调用一旦所有的项目迭代。像这样

    var arr="";
    var index=0;
    $('#sortable li').each(function () {  
        items += $(this).text();
        arr+="{field"+index+":" + field + , "plu"+index+":" + plu + "}";
    });
    insertCustomBCFields(arr);

同样更改ajax调用

   function insertCustomBCFields(arr) {
    alert(field + plu);
    $.ajax({
        type: "POST",
        url: 'ProductDefinition.aspx/insertBCCustomFields',
        data: {'arr':arr},
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function (data) {
            alert("Success");
        },
        failure: function (response) {
            alert("Insert Failed!");
        }
    });
   }

快乐编码:)