jQuery POST. Can't get Request parameters usin

2019-06-24 15:25发布

问题:

I have a jQuery post method with JSON data included.

In my httphandler, in the processRequest method, Request["Operation"] is null and none of my data is posted. I am in a SharePoint 2010 environment.

 public void ProcessRequest(HttpContext context)
    {
        try
        {
            string operation = context.Request["Operation"]; // Returns null

My JavaScript is as follows:

function CallService(serviceData, callBack) {

$.ajax({
    type: "POST",
    url: ServiceUrl,
    data: { Operation : "activate"},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        callBack(result);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(XMLHttpRequest.responseText);
    }
});

In the debugger in VS I can't find the posted values when I evaluate the HttpContext. In Firebug, the value is posted as valid JSON data. Any reason why I cant get the parameters?

Any help appreciated.

回答1:

Thanks for all your input guys. I have decided to read the input stream of the request instead and get a key value pair from that. I can access all my params that way.

I am also using the $.toJSON() function to pass my parameters to the Ajax call. The JsonConvert class is from JSON.Net assembly from Newtonsoft. I use it a lot and would highly recommend using it if you use any json serialisation stuff.

By the way, changing the quotes around the input params did work. I want to keep using one generic ajax function and use $.toJSON function and generally pass an object with all my parameters as the post data.

TextReader reader = new StreamReader(context.Request.InputStream);
        Dictionary<string, string> requestParams = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());      
        try
        {

            switch (requestParams["operation"])


回答2:

I changed contentType to application/x-www-form-urlencoded and it did a trick



回答3:

Maybe you're being restricted by the Same Origin Policy. Is ServiceUrl at the same hostname and domain as the calling page?



回答4:

Why are you overriding the contentType option in your $.ajax() call? If you omit that, do you still see null being sent in for the Operation value?

Also, I think the proper formatting for JSON data would be:

{"Operation": "activate"}

I think the JSON spec is specific about that, but most frameworks aren't as strict.