同时调用两个ajax会导致两个内部服务器错误

本文关键字:两个 内部 服务器 错误 调用 ajax | 更新日期: 2023-09-27 17:51:12

我有两个函数执行两个ajax调用。如果我调用一个函数而不调用另一个代码正常执行。但是如果我同时调用它们,我会得到两个内部服务器错误消息。我想每个功能一个。

这是我的代码:

   $(document).ready(function(){
         CategoryChangeState(@Model.CatId , subcategoryId);
         SubategoryChangeState(@Model.SubcatId);
    })
    public ActionResult ReturnListOfSubcategories( FormCollection collection ) {
            string categoryId = collection["result"];
            var subcategories = ProductManagerHelperClass.ReturnSubcategories(categoryId);
            return Json(subcategories);
    }
    public ActionResult ReturnListOfBrands() {
          var brands = ProductManagerHelperClass.ReturnBrands();
          return Json(brands);
    }
function CategoryChangeState(value ,  editPage) {
        .....
        $.ajax({
            type: "POST",
            url: "/ProductManager/ReturnListOfSubcategories",
            data: { result: value },
            datatype: "json",
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
        ...
}
function SubategoryChangeState(value) {
         ....
         $.ajax({
            type: "POST",
            url: "/ProductManager/ReturnListOfBrands",
            datatype: "json",
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
       ....
}

为什么我得到这些错误,我怎么解决它?

编辑

在调试时,我发现在这部分代码中:
 public static Dictionary<string , string> ReturnSubcategories(string categoryId)
    {
        int catId = int.Parse(categoryId);
        var subcategories = (from s in dataContext.SubCategories
                             where s.CatId == catId
                             select new
                                        {
                                            s.SubCatId,
                                            s.SubCatName
                                        }).ToDictionary(x => x.SubCatId.ToString(), x => x.SubCatName);
        return subcategories;
    } 

linq查询抛出异常:

InvalidOperationException ExecuteReader requires an open and available Connection. The connection's current state is closed.

同样,此异常仅在同时调用

同时调用两个ajax会导致两个内部服务器错误

两个函数时抛出

这是因为您使用静态类,(可能)在其中建立到数据库的连接。发生以下情况:

    线程1进入静态类,打开连接。
  1. 同时线程2进入相同的类,并使用相同的打开连接。
  2. 当线程1完成时,关闭打开的连接。
  3. 线程2抛出错误,因为没有打开的连接。

如果您不使用静态类实例化数据库连接,则不会发生这种情况。