简体   繁体   English

ajax jquery json返回500内部服务器错误(未定义),但webmethod起作用

[英]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. 我是jquery和json的新手,但我想弄清楚为什么getAreas()函数返回500 /内部服务器错误-未定义。 I checked the WebMethod and it is returning data and the getRegions() function works just fine. 我检查了WebMethod,它正在返回数据,并且getRegions()函数正常工作。 The VS project builds just fine. VS项目构建良好。 Any ideas? 有任何想法吗? The code is below: 代码如下:

C# Server Side C#服务器端

[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 的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 在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()处为{“ Message”:“无效的JSON原语:Dot4。”,“ StackTrace”:“在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal( Int32深度)\\ r \\ n在System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入,Int32 depthLimit,JavaScriptSerializer序列化器)\\ r \\ n在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer序列化器,字符串输入,类型类型,Int32 depthLimit)\\ r \\ n在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)\\ r \\ n在System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context) ,JavaScriptSerializer序列化程序)\\ r \\ n(位于System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext上下文))\\ r \\ n位于System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext上下文,WebServiceMethodData methodData) )","ExceptionType":"System.ArgumentException"} )“,” 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. 这很晚了,但是可能对某些旅行者有帮助...我也已经发现,与XML配合使用的Web方法在以JSON处理时可能会显示“内部服务器错误”。

In all my cases this has been down to one of the following. 在我所有的情况下,这都归结为以下情况之一。

1) I have a problem in my class being serialized. 1)我的课程被序列化时遇到问题。 Something I have excluded from XML serialization using [XmlIgnore] is giving problems in JSON (like a circular reference). 我使用[XmlIgnore]排除在XML序列化之外的东西给JSON提供了问题(例如循环引用)。 I fix this with the [ScriptIgnore] attribute. 我使用[ScriptIgnore]属性修复了此问题。

2) I have a problem in the client-side javascript that builds the JSON parameters into the web method. 2)我在客户端javascript中有一个问题,该问题将JSON参数构建到web方法中。 In this case the server returns a "500 Internal Server Error", which I find misleading and frankly incorrect. 在这种情况下,服务器返回“ 500 Internal Server Error”,我发现这具有误导性并且坦率地说是不正确的。 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). 查看上面的代码,问题可能只是“ Dot4”需要用引号引起来(它完全是错误消息指出的“无效的JSON原语”)。 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. 但是,由于错误消息显示“内部服务器错误”,因此您需要漫长的旅程,开始在服务器而不是客户端中查找问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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