开发者

How do I get Ajax request data with jQuery?

I have an Ajax request:

$.ajax({ url: "MyPage.aspx", 
    data: params,
    success: function(data) {
        // Check results                
        $('#testp').append(data.message);
        enableForm();
    },
    error: fu开发者_如何学Cnction() {
        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.


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/


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜