使用AJAX的ScriptManager异步从Web服务获取数据并抛出错误?

时间:2014-07-01 23:19:16

标签: javascript jquery asp.net ajax web-services

我在ASP.NET中有一个网站,我正在使用ScriptManager通过AJAX从WebService获取数据。

当加载default.aspx页面时,会触发onload事件并从我的Javascript调用getCategoryDataSet()函数。 javascript中的getCategoryDataSet()函数只是调用webservice中的方法来检索数据。

问题:

当调用getCategoryDataSet()时,这是我收到的错误消息:

“JavaScript运行时错误:无法获取属性' 0'未定义或空引用“ enter image description here

当触发getCategoryDataSet()函数时,似乎函数在收到来自Web服务的数据之前结束。我这样说是因为我在访问webservice的数据之前添加了一个alert()函数,似乎我在警告框上按下ok的时间足以从webservice调用中检索数据。

如何在不使用提醒按钮的情况下解决此问题,从而为通话留出更多时间?还是另一个问题?

以下照片显示使用提示框的代码: enter image description here enter image description here

这是我的解决方案资源管理器: enter image description here

我的default.aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="category_selection_02._default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="script/JScript_01_GetCategories.js"></script>
</head>
<body onload="getCategoryDataSet()">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService_GetCategories.asmx" />
        </Services>
    </asp:ScriptManager>
    <div>
    </div>
    <div id="divListBoxes">
        THIS DIV WILL BE POPULATED WITH LISTBOXES
    </div>
    </form>
</body>
</html>

我的WebService_GetCategories.asmx.cs代码:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService_GetCategories : System.Web.Services.WebService
{

    [WebMethod]
    public List<Category> GetCategoriesWebService(int index_left)
    {
        //Debug.WriteLine("in WEBMETHOD");
        List<Category> listCategory = new List<Category>();
        DataSet ds = (new DataBase_DataSet_Generator(index_left)).getDataSet();
        DataTable dt = new DataTable();


        dt = ds.Tables[0];

        foreach (DataRow dr in dt.Rows)
        {
            Category categoryFields = new Category();
            categoryFields.category_id = (int)dr["category_id"];
            categoryFields.index_left = (int)dr["index_left"];
            categoryFields.index_right = (int)dr["index_right"];
            categoryFields.categoryName = (dr["categoryName"]).ToString();
            //categoryFields.categoryInfo= (dr["categoryInfo"]).ToString();

            listCategory.Add(categoryFields);

            //Debug.WriteLine("This is the total items in the listCategory: "+ listCategory.Count);
        }


        return listCategory;
    }
}

我的JScript_01_GetCategories.js代码:

var public_categoryDataSet; //this is the category dataset retreived from the webservice


function getCategoryDataSet() {
    var index_left = 1;

    category_selection_02.WebService_GetCategories.GetCategoriesWebService(index_left, GetCategoryIdSuccessCallBack, GetCategoryIdFailedCallBack)

    function GetCategoryIdSuccessCallBack(results_from_webservice) {
        public_categoryDataSet = results_from_webservice;
    }

    function GetCategoryIdFailedCallBack(errors) {
        alert("AJAX Failed callback invalid data inserted in textbox");
    }
    alert("Alert Fired");  //<--if this alert() call is removed I get an error???
    alert(public_categoryDataSet[0].category_id);
}

1 个答案:

答案 0 :(得分:1)

正在发生的事情是你的函数getCategoryDataSet()正在执行,它正逐步执行代码 。换句话说:

  1. 设置var index_left = 1
  2. 调用AJAX调用,将两个回调绑定为返回参数
  3. (火警)
  4. alert category_id
  5. 基本上,只要达到第2步,它就会调用对Web服务的调用,然后继续执行,从而到达第4步并执行之前 Web服务已返回数据,返回空引用异常。将您的虚拟警报置于中间(步骤3)使其足够时间在您访问之前完成加载Web服务数据。

    解决方案

    您编写的任何从AJAX调用访问结果变量的代码都必须放在成功处理程序中。这有两个原因:

    1. 首先,在访问生成的变量之前,您需要确保AJAX调用已完成;因此将它放在成功处理程序中可以确保这一点。
    2. 其次,如果您的Web服务方法失败并且不返回任何变量会发生什么?访问它们会发生什么?大问题!
    3. 这就是成功错误回调的来源 - 它们应该包含应分别在每个场景下执行的代码。

      一些代码:

      function getCategoryDataSet() {
          var index_left = 1;
      
          category_selection_02.WebService_GetCategories.GetCategoriesWebService(
              index_left, 
              GetCategoryIdSuccessCallBack, 
              GetCategoryIdFailedCallBack);
      
          function GetCategoryIdSuccessCallBack(results_from_webservice) {
              public_categoryDataSet = results_from_webservice;
              //process public_categoryDataSet here
              alert(public_categoryDataSet[0].category_id);
          }
      
          function GetCategoryIdFailedCallBack(errors) {
              alert("AJAX Failed callback invalid data inserted in textbox");
          }
      
          alert("Alert Fired");  
          //don't process anything here as it will execute before the AJAX call completes
      }