Making a call to a page that returns JSON using ASP.net AJAX
I have a Page that expects a POST Request and returns some JSON. Essentially it's an .ashx Page, but that doesn't really matter.
When using jQuery, I would use jQuery.Post with "json" as dataType to simply make the POST request and get an object back. However, for the current project I mainly use ASP.net AJAX and I don't want to add jQuery just for the call.
For ASP.net AJAX, I only found information on how to call a "traditional" web service though, which means adding a asp:ServiceReference to the ScriptManager and having a "real" Web S开发者_StackOverflow社区ervice at the end.
Is there a simpler way to make a POST call to a Page? I could live with getting the raw JSON and then manually eval()ing it, but I don't want to create a full asmx web service (deploying them on SharePoint is a bit painful, and my ashx handler works fine)
Sys.Net.WebServiceProxy.invoke(url, methodName, useGet, parametersDictionary, onSuccess, onFailure, userContext, timeout);
All params optional except the first.
parametersDictionary is like { foo: bar } -- the parameters will be sent as JSON in the body if you are posting, or as parameters on the query string if it is GET (each parameter separately json serialized -- which btw means strings look like "foo", with the quotes).
onSuccess if a callback that takes the data as the first parameter (already deserialized object).
onFailure gets an error object as the first parameter which contains a get_message() method to get the error message, and some other things.
You can use the invoke method of the Sys.Net.WebServiceProxy class directly.
The method signature looks like this:
invoke(path, methodName, useHttpGet, parameters, succeededCallback, failedCallback, userContext, timeout);
Assuming that your service actually returns JSON, then the first argument to succeededCallback should be a JSON object.
Sys.Net.WebServiceProxy wasn't helpful because it seems to expect a real web service at the end - Request.Form was empty on the server side, parametersDictionary seems to be ignored. There also seems to be no override to wire up another executor instead.
I now solved it by manually creating a Sys.Net.WebRequest. I'l going to take a look at the jQuery sources as this approach is a lot more complex/"bare-metal", but as said, I don't want to add a dependency on jQuery if it isn't needed.
var ApplicationFunctions = {
showDialog: function(someParam, someOtherParam) {
var sb = new Sys.StringBuilder("Do you really want to do '");
sb.append(someParam);
sb.append("' ?");
var msg = sb.toString();
if (confirm(msg)) {
var myWebRequest = new Sys.Net.WebRequest();
myWebRequest.set_url('SomeService.ashx');
myWebRequest.set_httpVerb('POST');
// Manually build POST body. This would need escaping/urlencoding
// I think if I couldn't guarantee that the parameters are 'clean'
var bodySb = new Sys.StringBuilder("postParam=");
bodySb.append(someParam);
bodySb.append("&anotherPostParam=");
bodySb.append(someOtherParam);
var body = bodySb.toString();
myWebRequest.set_body(body);
myWebRequest.get_headers()["Content-Length"] = body.length;
// also check out usercontext to pass additional data into the completed function
// http://msdn.microsoft.com/en-us/library/bb397436.aspx
myWebRequest.add_completed(ApplicationFunctions.onCallCompleted);
myWebRequest.set_timeout(10 * 1000); // 10 seconds
myWebRequest.invoke();
}
},
onCallCompleted: function(response) {
if (response.get_timedOut()) {
alert("Timed Out!");
return;
}
if (response.get_statusCode() !== 200) {
alert("Status Code not OK");
return;
}
if (!response.get_responseAvailable()) {
alert("No data available?!");
return;
}
// Better use a JSON parser
// http://www.json.org/js.html
var responseData = eval('(' + response.get_responseData() + ')');
alert("Success: " + responseData.SomeField);
}
}
精彩评论