问题
Im constructing an array of objects like this:
var postData = [];
$.each(selectedFields, function (index, value) {
var testTitle = 'testing ' + index;
postData.push({title: testTitle, title2 : testTitle});
}
I then post it like this(note that i have tried a number of different aproaches):
$.post('SaveTitlesHandler.ashx', { form : postData }, function (data) {
console.log(data);
});
I then try to get the data in a handler...
public class SaveTitlesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string json = context.Request.Form.ToString();
}
}
I cant seem to get proper json out of the request. Anyone got any idea?
cheers.
twD
回答1:
You are not posting JSON. You are using application/x-www-form-urlencoded
. So inside the handler you could access individual values:
public void ProcessRequest(HttpContext context)
{
var title1 = context.Request["form[0][title]"];
var title2 = context.Request["form[0][title2]"];
var title3 = context.Request["form[1][title]"];
var title4 = context.Request["form[1][title2]"];
...
}
If you wanted to POST real JSON you need this:
$.ajax({
url: 'SaveTitlesHandler.ashx',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postData),
success: function(result) {
console.log(result);
}
});
and then inside the handler read from the request input stream:
public void ProcessRequest(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
The JSON.stringify
method converts a javascript object into a JSON string and it is a native method built-in modern browsers. You might also need to include json2.js if you want to support older browsers.
来源:https://stackoverflow.com/questions/6421351/post-json-object-array-to-ihttphandler