SyntaxError: JSON.parse

本文关键字:parse JSON SyntaxError | 更新日期: 2023-09-27 18:15:51

我试图从JSON调用简单的Web方法,但我得到错误。

在Chrome:

SyntaxError: unexpected token <</p>

Firefox:

SyntaxError: JSON.parse

Javascript代码:

 $(document).ready(function() {
     $('#<%=ddlTest.ClientID %>').change(function() {
         var value = $('#<%=ddlTest.ClientID %>').val();
         var req = $.ajax({
             type: "POST",
             url: "Test.aspx/getTest",
             data: "{Id: '" + value + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function(data) {
                 $(alert(data.d))
             },
             error: function(XMLHttpRequest, text, error) { alert(error); },
             failure: function(response) {
                alert(response.d);
             }
         })
    });
 });     

.aspx code:

<asp:DropDownList ID="ddlTest" AutoPostBack="false" runat="server">
    <asp:ListItem Value="0" Text="zero" />
    <asp:ListItem Value="1" Text="One" />
    <asp:ListItem Value="2" Text="Two" />
</asp:DropDownList>
<asp:Label ID="lblTest" runat="server" Text="hiii"/>

WebMethod:

[WebMethod] 
public static string getTest(string id)
{
    return id;
}

SyntaxError: JSON.parse

如果您在Firebug之类的程序中查看AJAX请求的响应,您将看到返回的是HTML标记而不是JSON。

这是因为您的data参数不太正确。因此,你所做的请求与任何可用的页面方法都不匹配,最终被处理得像对ASPX页面本身的常规请求一样。

由于HTML文档的第一个字符是JSON文档的无效第一个字符,JSON解析器将无法正确解析它。

要解决这个问题,更改您的data参数如下:
// Parameters to page methods are case sensitive. Id != id.
//
// Parameter names need to be quoted. ASP.NET will allow for both double and
//  single quotes, but technically only double quotes are valid JSON.
data: '{"id": "' + value + '"}",
在客户端手动构建JSON字符串很快就会变得混乱。您可能对使用JSON感兴趣。

我找到了解决问题的办法。我只是加了个傻瓜。我的网里有线。

<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>

remove 'return id';

相反,你必须将响应序列化为JSON并执行response write

    using System.Text;
    using System.Runtime.Serialization.Json;
    using System.IO;
...
    public static string ToJSON(this object obj)
            {
                string json = string.Empty;
                DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
                using ( MemoryStream ms = new MemoryStream() )
                {
                    ser.WriteObject(ms, obj);
                    json = Encoding.Default.GetString(ms.ToArray());
                }
                return json;
            }

HttpContext.Current.Response.Write(ToJSON(id));