与asp.net的jquery ajax无法正常工作

Pos*_*ing 6 c# asp.net ajax jquery c#-2.0

我准备把剩下的头发拉出来,所以如果你知道问题可能会帮助我...谢谢.我所有的谷歌搜索和搜索都没有得到回报.

首先,我使用的是jquery-1.7.2.min.js和ASP.net 2.0 Web表单.

我正在尝试使用jquery进行ajax调用,但不断收到语法错误/解析错误消息.我尝试了很多不同的方法但是当我将dataType设置为json时它们都会导致错误.

这就是我所拥有的:

$.ajax({
    type: "POST",
    url: "UserList.aspx/GetTestJson",
    data: {}, //have also tried "{}" and other options such as removing the line
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        alert('success');
    },
    //Using below instead of above makes no difference either
    //success: function(data){
    //  alert('success');
    //},
    error: function(jqXHR, textStatus, errorThrown){
        alert('errorThrown: ' + errorThrown);
    }
});
Run Code Online (Sandbox Code Playgroud)

和aspx页面方法:

[WebMethod]
public static string GetTestJson()
{
    return "Hello My World";
}
Run Code Online (Sandbox Code Playgroud)

我也试过设置一个Web服务,但得到了相同的结果.似乎回来的响应是页面的完整html或来自Web服务的xml,因为我将dataType设置为json,它在解析它时不成功.如果是这种情况,如何将响应设置为仅返回json?

这是我没有运气的其他事情:

[WebMethod]
public static string GetTestJson()
{
    HttpContext.Current.Response.ContentType = "application/json";
    string json = JavaScriptConvert.SerializeObject("Hello My World");
    return json;
}
Run Code Online (Sandbox Code Playgroud)

我通过jQuery获得的错误消息:

errorThrown.message = "Syntax error"
errorThrown.number = -2146827286
errorThrown.name = "SyntaxError"
textStatus = "parseerror"
jqXHR.status = 200
jqXHR.statusText = "OK"
jqXHR.readyState = 4
jqXHR.responseText = (the complete html of the page)
Run Code Online (Sandbox Code Playgroud)

任何想法或建议?

谢谢

Pos*_*ing 11

感谢@DaveWard和@CodeRoller的帮助,这导致了这个解决方案:

  1. 安装ASP.NET Ajax扩展(HERE)
  2. 添加对System.Web.Extensions.dll的引用
  3. 修改web.config以包含ScriptModule httpModule(见下文)

我的jQuery ajax调用和WebMethod仍然和我原来的帖子一样.

我的web.config已修改如下:

  <system.web>
    <compilation debug="true">
      <assemblies>
        <!-- A bunch of other assemblies here-->
        <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>
  </system.web>
Run Code Online (Sandbox Code Playgroud)

我希望其他人会觉得这很有用.

  • @SurajSingh你最受欢迎.我很高兴这篇文章可以帮助别人.我也很担心这个问题... =) (3认同)