简体   繁体   中英

ajax jquery json returns 500 internal server error (undefined) but webmethod works

I'm new to jquery and json and I'm trying to figure out why the getAreas() function returns a 500/Internal Server Error - undefined. I checked the WebMethod and it is returning data and the getRegions() function works just fine. The VS project builds just fine. Any ideas? The code is below:

C# Server Side

[WebMethod]
public static ArrayList GetRegionsArrayList()
{
    ArrayList arrayList = new ArrayList();
    foreach (DataRow dr in Utility.Regions().Rows)
    {
        arrayList.Add(new ListItem(dr["Region"].ToString(), dr["Dot4"].ToString()));
    }
    return arrayList;
}

[WebMethod]
public static ArrayList GetAreasArrayList(string Dot4)
{
    ArrayList arrayList = new ArrayList();
    foreach (DataRow dr in Utility.Areas(Dot4).Rows)
    {
        arrayList.Add(new ListItem(dr["Area"].ToString(), dr["Dot6"].ToString()));
    }
    return arrayList;
}

JavaScript

<script type="text/javascript" language="javascript">
    function PopulateControl(list, control) {
        if (list.length > 0) {
            control.removeAttr("disabled");
            control.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(list, function () {
               control.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        } else {
            control.empty().append('<option selected="selected" value="0">Not available<option>');
        }
    }

    function getRegions() {
        $.ajax({
            type: "POST",
            url: "Demo.aspx/GetRegionsArrayList",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnRegionsPopulated,
            error: function (response) {
                alert(response.status + ' ' + response.statusText);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }

    function getAreas() {
        $.ajax({
            type: "POST",
            url: "Demo.aspx/GetAreasArrayList",
            data: "{Dot4: ' + $('#<%=DDL_Region.ClientID%>').val() + '}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnAreasPopulated,
            error: function (response) {
                alert(response.status + ' ' + response.statusText);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }

    function OnRegionsPopulated(response) {
        PopulateControl(response.d, $("#<%=DDL_Region.ClientID%>"));
    }

    function OnAreasPopulated(response) {
        PopulateControl(response.d, $("#<%=DDL_Area.ClientID%>"));
    }
</script>

Controls

<select id="Select1" onchange="getRegions();">
<select id="DDL_Region" onchange="getAreas();" runat="server"></select>
<select id="DDL_Area" runat="server"></select>

The error details:

{"Message":"Invalid JSON primitive: Dot4.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\\r\\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\\r\\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\\r\\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\\r\\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\\r\\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\\r\\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\\r\\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData )","ExceptionType":"System.ArgumentException"}

This is late, but it may help some travellers...I too have discovered that web methods that work just fine with XML may give "Internal Server Error" when processed as JSON.

In all my cases this has been down to one of the following.

1) I have a problem in my class being serialized. Something I have excluded from XML serialization using [XmlIgnore] is giving problems in JSON (like a circular reference). I fix this with the [ScriptIgnore] attribute.

2) I have a problem in the client-side javascript that builds the JSON parameters into the web method. In this case the server returns a "500 Internal Server Error", which I find misleading and frankly incorrect. This is not an internal server error, but a mal-formed client request.

Looking at the code above the problem is probably just that "Dot4" needs to be in quotes (it is an "Invalid JSON primitive" exactly as the error message states). However, as the error message gives "Internal Server Error" you start off on a long journey looking for a problem in the server and not the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM