Reputation: 1122
I have
var pageData = {
query: null,
pageNumber: 0,
pageSize: 30};
When I make an ajax get:
$.ajax({
type: 'GET',
url: '/Ajax/GetSuggestions',
data: pageData,
success: function (response) {}
The request show in firebug: http://localhost:31198/Ajax/GetSuggestions?query=null&pageNumber=1&pageSize=30
At server side (ASP .NET MVC3), I received query = null in string, not null data(what I need). How can I fix it without using delete method of javascript to remove null value?
Upvotes: 3
Views: 2207
Reputation: 49104
There are multiple ways to send data "over the wire". The standard one for sending form data to the server is url encoding. A second way is to send a JSON object. (A transmission detail is that the JSON would be url-encoded. But that's only a transmission detail.) A third way is to use XML.
As @jfriend00 shows in his answer, there are multiple, hacky ways to send a "null" value via url encoding. You should use the one which your server side stack best supports.
Re: why the string "null" What's happening is that the Javascript value null needs to be converted to a value that can be sent via HTTP ("over the wire"). The default way to do that is to use the string null. The problem is that the url encoding scheme only sends things as strings. So it doesn't have an automatic way to send the value null vs teh string null. The usual work around is an empty string, "".
But this can also raise an issue on your server-side since the string "" is not equal to the value null in most computer languages. So you will need to make appropriate comparisons or conversions. Eg does "" == false in your server software?
Using JSON for the data encoding is the other technique.
JSON directly supports a null value. It is is supposed to transmit it as null
. See JSON spec (not so obvious, search the page for null) and IBM docs
The way you receive null data in JSON is the bareword null
. If you're using JSON, note that you do not receive the string null, you receive the JSON keyword null. Your JSON receiver/decoder should know the difference. If it doesn't, then it is faulty.
Upvotes: 2
Reputation: 707308
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?query=&pageNumber=1&pageSize=30
Then, you have to set query property to ""
(an empty string).
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?&pageNumber=1&pageSize=30
Then, you have to remove to remove the query
property from the pageData object by either not putting it there in the first place or by using delete pageData.query
to remove it.
Upvotes: 2
Reputation: 179046
When the request string is being built in jQuery, it's using every property on the data
object it can find.
All you need to do to remove a property is delete
the property:
delete pageData.query;
Upvotes: 0