代码之家  ›  专栏  ›  技术社区  ›  Mike Webb

如何使用jQuery获取Ajax请求数据?

  •  3
  • Mike Webb  · 技术社区  · 15 年前

    我有一个Ajax请求:

    $.ajax({ url: "MyPage.aspx", 
        data: params,
        success: function(data) {
            // Check results                
            $('#testp').append(data.message);
            enableForm();
        },
        error: function() {
            alert('Unable to load the permissions for this user level.\n\nYour login may have expired.');
            enableForm();
        },
        dataType: "json"
    });
    

    在请求页面上,有一个C#代码在加载页面的末尾执行此操作:

    Response.AppendHeader("X-JSON", result);
    

    { "success": true, "message": "SUCCESS", "user_level": 25, "switches": [ { "number": 30, "is_enabled": false, "is_default": false }, { "number": 30, "is_enabled": false, "is_default": false } ]}
    

    请求成功返回,但“data”为空。我错过了什么?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Dave Ward    15 年前

    您的主要问题似乎是在HTTP报头中返回JSON数据,而不是作为响应的内容。你可能想这样做:

    Response.ContentType = "application/json";
    Response.Write(result);
    Response.End();
    

    public class PermissionsResult
    {
      public bool success;
      public string message;
      public int user_level;
    
      public List<Switch> switches;
    }
    
    public class Switch
    {
      public int number;
      public bool is_enabled;
      public bool is_default;
    }
    
    // The combination of a WebMethod attribute and public-static declaration
    //  causes the framework to create a lightweight endpoint for this method that
    //  exists outside of the normal Page lifecycle for the ASPX page.
    [WebMethod]
    public static PermissionsResult GetPermissions(int UserLevel)
    {
      PermissionsResult result = new PermissionsResult();
    
      // Your current business logic to populate this permissions data.
      result = YourBusinessLogic.GetPermissionsByLevel(UserLevel);
    
      // The framework will automatically JSON serialize this for you.
      return result;
    }
    

    您必须将其与自己的服务器端数据结构相适应,但希望您能理解。如果已经有可用所需数据填充的现有类,则可以使用这些类,而不是为传输创建新类。

    call an ASP.NET AJAX Page Method with jQuery

    $.ajax({
      // These first two parameters are required by the framework.
      type: 'POST',
      contentType: 'application/json',
      // This is less important. It tells jQuery how to interpret the
      //  response. Later versions of jQuery usually detect this anyway.
      dataType: 'json',
      url: 'MyPage.aspx/GetPermissions',
      // The data parameter needs to be a JSON string. In older browsers,
      //  use json2.js to add JSON.stringify() to them.
      data: JSON.stringify({ UserLevel: 1}),
      // Alternatively, you could build the string by hand. It's messy and
      //  error-prone though:
      data: "{'UserLevel':" + $('#UserLevel').val() + "}",
      success: function(data) {
        // The result comes back wrapped in a top-level .d object, 
        //  for security reasons (see below for link).
        $('#testp').append(data.d.message);
      }
    });
    

    关于数据参数,以下是需要字符串的信息: http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/

    此外,这里还有更多关于使用JSON.stringify文件()方法: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

    .d问题一开始可能令人困惑。基本上,JSON会像这样返回,而不是像您预期的那样:

    {"d": { "success": true, "message": "SUCCESS", "user_level": 25, "switches": [ { "number": 30, "is_enabled": false, "is_default": false }, { "number": 30, "is_enabled": false, "is_default": false } ]}}
    

    http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

        2
  •  1
  •   Silkster    15 年前

    答案应该是:

    在ajax设置的url值末尾添加方法名:

    确保使用该方法指向正确的页面,并确保该方法具有WebMethod()属性。


    $。ajax几乎可以为您处理所有事情。如果AJAX调用成功,返回数据将作为参数传递给success函数,即:

    success: function (data) { 
        //do something 
    }
    

    “的值”数据.消息仅当“message”是返回数据的属性时,才可用。在您的例子中,id为“testp”的元素应该接收数据.消息,但对象的其余部分未被使用。

    非常棒的博客,您可以查看AJAX for.Net的所有内容: http://encosia.com/

    http://www.json.org/js.html )测试返回的数据。只需添加

    alert(JSON.stringify(data));