简体   繁体   中英

$.post(…) not recognizing JSON body

I'm trying to do a POST request to the server like this:

var body = {
    PatientAgeFilter: {
        CompareOperator: parseInt(self.patientAge()),
        MoreThanVal: {
            AgeSpecifier: 0,
            AgeValue: parseInt(self.patientAgeLow())
        },
        LessThanVal: {
            AgeSpecifier: 0,
            AgeValue: parseInt(self.patientAgeHigh())
        }
    }
};

$.post(url, body, self.results, "json").done(function () {
    console.log("request done!");
    console.log(self.results());
});

The URL is set correctly, self.results is a Knockout.JS observableArray() , and the body is set as above.

Server side, this is the code handling the request:

[HttpPost]
public IQueryable<Measurement> GetMeasurements(MeasurementQuery queryOptions)
{
    ...
    if (queryOptions != null) {
        if (queryOptions.PatientAgeFilter.CompareOperator != CompareOperator.Any) {
            ...
        }
    }
}

I've set a breakpoint on if (queryOptions != null) , and queryOptions is not null. But the content of queryOptions stays default, even though I specify the fields in body (fe the CompareOperator should equal 3, but it stays 0 - which equals CompareOperator.Any ), so the body of the POST request isn't parsed properly.

Can anybody help me out here as to why this happens? Much appreciated!

Your post method is incorrect in 2 ways:
1. As already stated in comments, you should use JSON.stringify for your data. (see update below)
2. Third parameter (if present) must be a success callback .

So, this variant should work:

...
$.post(url, JSON.stringify(body), function(results) {
    self.results(results);
}, "json");

UPDATE 1:

The problem is not in JSON.stringify indeed, since WEB Api by default supports application/x-www-form-urlencoded which is default content-type for $post() . So, my next guess that the problem is with your server model. Make sure that CompareOperator , MoreThanVal and LessThanVal are actually properties, not fields (and all their children, which you would like to bind). WEB API doesn't bind fields.

The problem was - as I thought - that the request body didn't get through to the server properly. I changed this

$.post(url, body, self.results, "json");

to the following

$.ajax({
    url:url,
    type:"POST",
    data:JSON.stringify(body), //necessary for the data to be parsed properly
    contentType:"application/json; charset=utf-8", //important!
    dataType:"json",
    success: function(results){
        self.results(results);
    }
});

And now it works as it should.

I used this SO question for the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM