向webservice发送多个ajax请求

时间:2013-12-15 17:47:13

标签: jquery asp.net ajax wcf

我有这行代码向wcf发送多个ajax请求

$(".cWarpO").each(function () {

                  if ($(this).find(".newId").length > 0) {
                        counter++;

                        var Mapping = new Array();
                        Mapping[0] = counter;
                        Mapping[1] = $(this).find(".idN").html(); //new id
                        Mapping[2] = $(this).find(".idO").html();
                        Mapping[3] = newCourseId;
                        Mapping[4] = courseOldId;
                        Mapping[5] = isGenric;
                        Mapping[6] = oldGenricCourse;

                        $.ajax({
                            url: "/WebServices/general.svc/mappingCourses",
                            type: "POST",
                            data: JSON.stringify({ Mapping: Mapping }),
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {



                            }
                        });


                    }

                });

webservice操作是更新db。 由于jquery ajax工作不同步,它发送的服务器multipal请求以错误结束:“尝试对不是套接字的操作进行操作”

我感觉很糟糕,因为数据库每次都试图打开新连接。

知道如何以同步的方式循环数组吗?

由于

Baaroz

1 个答案:

答案 0 :(得分:0)

不是同步执行可能会锁定客户端浏览器(请参阅this post),为什么不使用递归发送请求 - 即每当请求完成发送下一个请求时:

var mapCourse = function($ele, index) {
    if(index < $ele.length) {
            //stuff
            $.ajax({
                url: "/WebServices/general.svc/mappingCourses",
                type: "POST",
                data: JSON.stringify({ Mapping: Mapping }),
                dataType: "json",
                contentType: "application/json; charset=utf-8",//you don't need to set this
                success: function (data) {
                    //stuff

                    mapCourse($ele, index + 1);
                }
            });
        }
    }
}

mapCourse($(".cWarpO"), 0);