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

发布于 2024-09-15 12:01:16 字数 809 浏览 4 评论 0原文

我有一个 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# 代码在 Page_Load 末尾执行此操作:

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 } ]}

请求成功返回,但“数据”为空。我缺少什么?

谢谢。

I have an Ajax request:

$.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"
});

On the request page there is C# code that does this at the end of Page_Load:

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

'result' is formatted like this:

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

The request returns successfully, but 'data' is null. What am I missing?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

顾北清歌寒 2024-09-22 12:01:19

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

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

这可能会解决您眼前的问题,但我强烈建议您避免使用 ASPX 页面的直接输出的方法。当您真正想要的只是一个简单的 JSON 端点时,到达 Page_Load 点会涉及很多不必要的开销。更不用说,手动处理 JSON 序列化是不必要的。

如果您从服务器端的对象构建 JSON 字符串,则可以使用 ASP.NET AJAX“页面方法”直接返回该字符串并让框架处理序列化。像这样:

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;
}

您必须将其适合您自己的服务器端数据结构,但希望您明白这一点。如果您已经拥有可以填充所需数据的现有类,则可以使用这些类而不是创建新类来进行传输。

调用 ASP。 NET AJAX 页面方法与 jQuery,您需要在 $.ajax() 调用上指定几个额外的参数:

$.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);
  }
});

关于 data 参数,这里是关于它需要是字符串的信息: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-writing-change- Between-versions-of-aspnet-ajax/

Your main problem seems to be that you're returning the JSON data in an HTTP header instead of as the content of the response. You probably want to do something like this:

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

That might fix your immediate problem, but I would strongly recommend that you avoid the approach of using an ASPX page's direct ouput. There's a lot of unnecessary overhead involved in getting to the point of Page_Load, when all you really want is a simple JSON endpoint. Not to mention, manually handling the JSON serialization isn't necessary.

If you're building that JSON string from an object on the server-side, you can use an ASP.NET AJAX "Page Method" to return that directly and let the framework handle serialization. Like this:

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;
}

You'll have to fit that to your own server-side data structures, but hopefully you get the idea. If you already have existing classes that you can populate with the data you need, you can use those instead of creating new ones for the transfer.

To call an ASP.NET AJAX Page Method with jQuery, you need to specify a couple extra parameters on the $.ajax() call:

$.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);
  }
});

Regarding the data parameter, here is info on it needing to be a string: http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/

Also, here is more on using the JSON.stringify() approach: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

The .d issue is one that can be confusing at first. Basically, the JSON will come back like this instead of how you might expect:

{"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 } ]}}

It's easy to account for once you expect it. It makes your endpoint more secure by mitigating against a fairly treacherous client-side exploit when the top level container is an array. Not applicable in this specific case, but nice to have as a rule. You read more about that here: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

一刻暧昧 2024-09-22 12:01:19

答案应该是:

将方法名称添加到 ajax 设置的 url 值末尾:

url: "MyPage.aspx/method"

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


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

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

仅当“message”是返回数据的属性时,“data.message”的值才可用。在您的情况下,id为“testp”的元素应该接收“data.message”的值,但对象的其余部分没有被使用。

很棒的博客,供您查看有关 .Net 的 AJAX 的所有内容:http://encosia.com/

我经常使用 JSON 库 (http://www.json.org/js.html)测试返回什么数据。只需添加

alert(JSON.stringify(data));

到您的成功函数中即可

Answer should be:

add method name to end of your url value of the ajax settings:

url: "MyPage.aspx/method"

Make sure you're pointing to the correct page with the method and make sure the method has the WebMethod() attribute.


$.ajax pretty much handles everything for you. The return data, if the AJAX call was successful, is passed to the success function as an argument, i.e.:

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

The value for "data.message" is only available if "message" is a property of the data returned. In your case, the element with id "testp" should receive the value for "data.message", but the rest of the object isn't being used.

Great blog for you to check out for all things AJAX for .Net: http://encosia.com/

I often use the JSON lib (http://www.json.org/js.html) to test what data is returned. Just add

alert(JSON.stringify(data));

to your success function

樱花细雨 2024-09-22 12:01:19

我最近很幸运,这是我所做的帖子,那里有很多好信息的链接!

无法让 jQuery Ajax 解析 JSON Web 服务结果

I had some luck recently, here is the post I did, and there is links to lots of good info there!

Can't get jQuery Ajax to parse JSON webservice result

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文