jQuery.ajax()不总是有效吗?是否容易发生错失?

时间:2014-12-17 16:47:25

标签: javascript c# jquery asp.net-ajax

我的页面上有一个$ .ajax函数,用于根据服务类型选择填充设施下拉列表。如果我在两个选项之间来回更改我的服务类型选择,则随机设施下拉列表中的值将保持不变并且不会更改。有办法防止这种情况吗?我做错了吗?

的Javascript

function hydrateFacilityDropDownList() {
        var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
        var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
        var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
        var tableName = "resultTable";

        $.ajax({
            type: 'POST',
            beforeSend: function () {

            },
            url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
            data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                a(data);
            }
            ,error: function () {
                alert('HydrateFacilityDropDownList error');
            }
            , complete: function () {

            }
        });
    }

function a(data) {
        var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
        var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
        var tableName = "resultTable";

        if (facilityDropDownList.value != "") {
            selectedFacilityID = facilityDropDownList.value;
        }

        $(facilityDropDownList).empty();
        $(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
        $(data.d).find(tableName).each(function () {
            var OptionValue = $(this).find('OptionValue').text();
            var OptionText = $(this).find('OptionText').text();

            var option = $("<option>" + OptionText + "</option>");
            option.attr("value", OptionValue);

            $(facilityDropDownList).append(option);
        });

        if ($(facilityDropDownList)[0].options.length > 1) {
            if ($(facilityDropDownList)[0].options[1].text == "In Home") {
                $(facilityDropDownList)[0].selectedIndex = 1;
            } 
        }

        if (TryParseInt(selectedFacilityID, 0) > 0) {
            $(facilityDropDownList)[0].value = selectedFacilityID;
        }

        facilityDropDownList_OnChange();
    }

背后的代码

[WebMethod]
    public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
    {

        List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
        List<Facility> facilities = Facility.GetAllFacilities().ToList();
        if (svcItems != null)
        {
            // Filter results
            if (svcItems.Any(si => si.RequireFacilitySelection))
            {
                facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
            }
            else
            {
                facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
            }

            if (serviceTypeID == 0)
            {
                facilities.Clear();
            }
        }
        return ConvertToXMLForDropDownList(tableName, facilities);
    }

public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
    {
        // Create dummy table
        DataTable dt = new DataTable(tableName);
        dt.Columns.Add("OptionValue");
        dt.Columns.Add("OptionText");

        // Hydrate dummy table with filtered results
        if (genList is List<Facility>)
        {
            foreach (Facility facility in genList as List<Facility>)
            {
                dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
            }
        }

        if (genList is List<EmployeeIDAndName>)
        {
            foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
            {
                dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
            }
        }

        // Convert results to string to be parsed in jquery
        string result;
        using (StringWriter sw = new StringWriter())
        {
            dt.WriteXml(sw);
            result = sw.ToString();
        }

        return result;
    }

1 个答案:

答案 0 :(得分:0)

$get返回XHR对象而不是成功调用的返回值,$ get函数不是同步的,所以你应该等待成功并检查从调用返回的数据

这两行与你期望的不同

var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;

更改为与此类似的内容

var facilityDropDownList;

$.ajax({
      url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
      type: 'get',
      dataType: 'html',
      async: false,
      success: function(data) {
          facilityDropDownList= data;
      } 
 });