IE9 jQuery AJAX GET错误“无法处理数据”

时间:2015-07-06 18:51:52

标签: jquery ajax

我有一个返回MVC partialView(返回html)的jQuery Ajax get请求。该请求在除IE9之外的所有浏览器中都能正常工IE9返回错误消息“无法处理数据”。我使用的是jQuery 1.11.4版 这是我的AJAX请求。

$.ajax({
            url: 'AddressTypesListChange',
            type: "GET",
            data: { 'addressType': $("#AddressTypeslist").val(), 'addressId': modelObj, 'type': $('#AddOrEdit').val(), 'companyName': $('#hdncompanyName').val() },
            cache: false,
            dataType: "text",                
            complete: function () {
                alert("AJAX - complete()");
            },
            success: function (data) {                    
                $('#AddEditAddressPlaceHolder').html(data);
            },                
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }                
        });
    }
});

我尝试了类XmlHTTP请求,这似乎正在起作用。这是XMLHttpRequest的工作原理:

var xhr = new XMLHttpRequest();
            xhr.open('Get', encodeURI('/Address/AddressTypesListChange?addressType=' + $("#AddressTypeslist").val() + '&addressId=' + modelObj + '&type=' + $('#AddOrEdit').val() + '&companyName=' + $('#hdncompanyName').val()));
            xhr.onload = function () {
                if (xhr.status === 200) {
                    $('#AddEditAddressPlaceHolder').html(xhr.responseText);
                    //alert('User\'s name is ' + xhr.responseText);
                }
                else {
                    alert('Request failed.  Returned status of ' + xhr.status);
                }
            };
            xhr.send();

以下是我需要在结果中返回的部分视图:

@using System.Collections.Generic
@using System.Web.UI.WebControls    
@model company.Model.Models.MemberAddressDetails
@{
    SelectListItem[] addressTypes = (SelectListItem[])ViewBag.AddressTypes;
    SelectListItem[] appCountryCodeList = (SelectListItem[])ViewBag.ApplicationCountries;
    var companyName = ViewBag.CompanyName;
    if (string.IsNullOrEmpty(companyName))
    {
        companyName = Model.CompanyName;
    }
}@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "frmWorkAddress", id = "frmWorkAddress" }))
{
    <div class=" row top-buffer-10">
        <div class="col-md-3 text-left">
            @Html.Label("Company Name:", new { @class = "control-label section_detail-title required" })
        </div>
        <div class="col-md-4">
            @Html.TextBox("CompanyName", Model.CompanyName, new { @class = "Formcontrol section_detail ", Name = "CompanyName" })
            @Html.ValidationMessageFor(model => companyName, "", new { @class = "text-danger" })
        </div>
        <div class="col-md-5 padding-Bottom">
            <input type="submit" value="Find Company" class="btn-smallpad btn-success section_detail-font-14" onclick="javascript: submitcompanyfind();" />
            @Html.ActionLink("Cancel", "Index", "Address", new { @class = "linkbutton padding-left-20" })

        </div>
    </div>
    <br />
    //second part

    <div id="hdnDivComapnyfinder" name="hdnDivComapnyfinder" style="display:none">
        <input type="hidden" name="hdnSelectedAddressId" id="hdnSelectedAddressId" />
    <input type="hidden" id="hdnSelectedcompany" name="hdnSelectedcompany" />
        <div class="row">
            <div id="CompanyList" class=" col-md-12 padding-all">
                <table id="CompanyList_table" class="table table-condensed table-hover table-striped">
                    <thead class="CompanyFinder-TableHeader-bgcolor">
                        <tr>
                            <th class="section_detail-title">Select</th>
                            <th class="section_detail-title">Address</th>
                        </tr>

                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div> @*end company list*@
            <div class="col-md-5">
                <input type="button" value="Next" class="btn btn-success " onclick="javascript: passCompanyInfo2mainAddresscontrol();" />
                @Html.ActionLink("Cancel", "Index", "Address", new { @class = " linkbutton padding-left-20" })
            </div>
        </div>
    </div>
}
        <script>
            $(function(){
                $("#frmWorkAddress").validate({
                    rules: {
                        CompanyName: {
                            required: true
                        },

                    },
                    messages: {
                        CompanyName: {
                            required: "Required"
                        },
                    },
                    errorClass: "validationError",
                    submitHandler: function (form) {
                        if ('console' in window) console.log("in find company");
                        $.ajax({
                            url: 'FindCompanyList',
                            type: 'Post',
                            data: $(form).serialize(),
                            success: function (data) {
                                var count = Object.keys(data).length;
                                //load the company table rows
                                LoadCompanyList(data);

                                $("#hdnDivComapnyfinder").show();
                            },
                            error: function (xhr, ajaxOptions, thrownError) {

                            }
                        });

                    }
                });

            }); 


            function submitcompanyfind() {

                $("#frmWorkAddress").submit();
            }
            function LoadCompanyList(data) {

                var tablerowshtml;
                $.each(data, function (i) {
                    var companyName = data[i].AddressLabelName;
                    var companywholeAddress = '<b>'+ companyName + '</b><br>' + data[i].AddressLine1 + ' ' + data[i].AddressLine2 + '<br>' + data[i].City + '  ' + data[i].State + ' ' + data[i].PostalCode;
                    var PassAddressId = data[i].AddressId;
                    var companyId = data[i].MemberId;
                    tablerowshtml += "<tr><td><input type='radio' id='SelectCompany' name='SelectCompany' onclick='PassAddressId(" + companyId +"," + PassAddressId + ")' /></td><td class='section_detail'>" + companywholeAddress + '</td></tr>';
                });
                tablerowshtml += "<tr><td><input type='radio' id='SelectCompany' name='SelectCompany' onclick='PassAddressId(0,0)' /></td><td class='section_detail'>" + 'None of the Above</td></tr>';
                $('#CompanyList_table tbody').empty();
                $('#CompanyList_table tbody').append(tablerowshtml);

            }

            function passCompanyInfo2mainAddresscontrol() {

                var selectedCompanyId = $('#hdnSelectedcompany').val();
                var searchedCompanyName = $('#CompanyName').val();
                var selectAddressId = $('#hdnSelectedAddressId').val();

                $.ajax({
                    url: 'GetEditCompanyAddress',
                    type: 'Get',
                    data: { 'companyID': selectedCompanyId, 'companyName': searchedCompanyName, 'AddressId': selectAddressId },
                    success: function (data) {
                        //$('#AddEditAddressPlaceHolder').html("");
                        $('#AddEditAddressPlaceHolder').html(data);
                        $('[name="HomeCountryDropdown"]').trigger('change');
                    },
                    failure: function (errMsg) {
                        alert(errMsg);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        //  alert(xhr.responseText);
                        //  alert(thrownError);
                    }
                });
            }//end function passCompanyInfo2mainAddresscontrol


            function PassAddressId(companyId,addressId)
            {              
                $('#hdnSelectedcompany').val(companyId);
                $('#hdnSelectedAddressId').val(addressId);
            }
        </script>

这是我的控制器动作:

[HttpGet]
        public PartialViewResult AddressTypesListChange(string addressType, string addressId, string type,string companyName)
        {
            var memberAddressDetails = new MemberAddressDetails();
            var applicationDetails = MvcApplication.Container.Resolve<IApplicationDetails>();

            var applicationCountries = applicationDetails.GetApplicationCoutries();
            ViewBag.ApplicationCountries = Helper.Convert2SelectListItem(applicationCountries);
            var addressTypes = applicationDetails.GetApplicationCodes(AppCodes.AddressType).Where(x => x.Code != "BULK").ToList();
            ViewBag.AddressTypes = Helper.Convert2SelectListItem(addressTypes);
            ViewBag.AddressType = addressType;

            var memberId = GetKeyValues.GetMemberId();
            var memberAddress = MvcApplication.Container.Resolve<IMemberAddressDetails>();
            if (!string.IsNullOrEmpty(addressId))
            {
                CustomLogger.LogEvent(EventType.Information, "Call GetAddressDetails to get Address info", CategoryType.General);
                var memberAddressDetailslist = memberAddress.GetAddressDetails(memberId);
                if (memberAddressDetailslist.Results.Success)
                {
                    memberAddressDetails = memberAddressDetailslist.SingleOrDefault(x => x.AddressId==Convert.ToInt32(addressId));
                }
            }

            if (!string.IsNullOrEmpty(companyName) && !string.IsNullOrEmpty(companyName.Trim()))
            {
                memberAddressDetails.CompanyName = companyName;
            }


            if (type == "edit" && memberAddressDetails != null)
            {
                return PartialView("_HomeAddress", memberAddressDetails);
            }
            if (addressType.ToLower().Equals("home") || addressType.ToLower().Equals("university"))
            {

                return PartialView("_HomeAddress", memberAddressDetails);
            }
            else if (addressType.ToLower().Equals("work"))//add partial view
                return PartialView("_EditAddressChangeCompany", memberAddressDetails);
            else
                return PartialView("_EditAddressChangeCompany", memberAddressDetails); //edit partial view
        }

1 个答案:

答案 0 :(得分:-1)

你能发布你正在呼叫的ActionResult吗?如果不知道你要回来了什么,很难知道问题是什么。

Knee-jerk的反应是将dataType:text改为html

$.ajax({
        url: 'AddressTypesListChange',
        type: "GET",
        data: { 'addressType': $("#AddressTypeslist").val(), 'addressId': modelObj, 'type': $('#AddOrEdit').val(), 'companyName': $('#hdncompanyName').val() },
        cache: false,
        dataType: "html",                
        complete: function () {
            alert("AJAX - complete()");
        },
        success: function (data) {                    
            $('#AddEditAddressPlaceHolder').html(data);
        },                
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }                
    });
}
});  

不知道更多,很难说。

编辑:另外,您是否考虑过将您的ajax方法从'GET'更改为'POST',并标记您的ActionResult以反映这一点?

编辑2:请将以下内容视为.ajax()代码的更新:

$.ajax({
        url: 'AddressTypesListChange',
        type: "GET",
        data: { 'addressType': $("#AddressTypeslist").val(), 'addressId': modelObj, 'type': $('#AddOrEdit').val(), 'companyName': $('#hdncompanyName').val() },
        cache: false,
        dataType: "html"
})
        .done(function( data, textStatus, jqXHR )
        {
            $('#AddEditAddressPlaceHolder').html(data);
            //successful call
        })
        .always(function( data, textStatus, jqXHR )
        {
            alert("AJAX - complete()");
            //complete/finally (will run regardless of success or failure)
        })
        .fail(function( data, textStatus, jqXHR )
        {  
            //In this case, jqXHR represents the errorThrown.
            alert(jqXHR);
        });  

总的来说,似乎你的语法可能有问题,因为代码在其他浏览器中工作的可能性不大,但在IE9中则不然,这是一个返回数据问题。根据{{​​1}}规范,自jQuery 1.8起,.ajax()completesuccess回调已被弃用,首选方法是上述Promise样式方法链接。

jQuery规范:http://api.jquery.com/jquery.ajax/