Accessing Data in Httphandler sent using post request
I have created a httphandler. Everything is working fine If you take the request type GET. But I really don't want GET request due to security reasons.
I am making a POST request using Jquery using following code:
$.ajax({
type: "POST",
async: false,
url: "SaveAccounts",
data: { a: "Sent Data" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(a) {
alert(a);
},
error: function OnError(request, status, error) {
alert('Error: ' + request + ' ' + status + ' ' + error);
},
complete: function () {
}
});
And the code for processing request is:
context.Response.ContentType = "application/json; charset=utf-8"
Dim s As开发者_如何学Go String = context.Request.Params("a")
context.Response.Write(JsonConvert.SerializeObject(s))
This code is returning 'null' in javascript alert in client side.
Please note every thing is working fine when request type is changed to GET in $.ajax() function.
I have also tried to access posted data using context.Request.Form("a") and context.request.SserverVariables("a")
context.request.Params is a combined collection of 'Form', 'ServerVariables', 'Cookies' etc.
Please tell me where I am going wrong...??
Thanks for looking....
This is working by just removing contentType and dataType specification from the request. Anything other than this will remain unchanged.
Try
data: { "a=Sent Data" },
e.g. from http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Also the HttpHandlers don't like JSON data so get rid of the contentType and the dataType.
Escaping it - a more complete example
var dataString = "{ 'first' : '" + escape($('#fname').val()) +
"', 'mail' : '" + escape($('#tbMail1').val()) +
"', 'mailinglist' : '" + $("input[name='ml']:checked").val() +
"' }";
/*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;)
$.ajax({
type: "POST",
url: "myAjaxHandler.asmx/ProcessSampleForm",
data: dataString,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".loadingimg").fadeOut();
window.location.replace(msg.d);
},
error:function(xhr,err){
$(".loadingimg").fadeOut();
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
Taken from http://www.jphellemons.nl/post/JQuery-with-webform-input-validation-ajax-posting-json-to-aspnet-C.aspx
精彩评论