Reputation: 7622
This is what I doing to build the data:
for (var i = args.length; i < args.length; i += 2) {
if (args.length != 0) args += ',';
args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"';
}
This is how I am calling:
$.ajax({
type: "GET",
url: "/blog/GetPosts",
//data: "{" + args + "}", <- gives 500 in 1.6 but works in 1.3
data: "app=blog&id=100&page=2&pagesize=10", <- this works
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {},
error: function (xhr, status, error) {}
});
How to build the data with multiple parameters and pass to controller? I need to loop and build the data since I have variable length of parameters.
Note that this works: data: "app=blog&id=100&page=2&pagesize=10"
But I can have &abc=something in the data itself which will be treated as another parameter.
Thanks for reading
Upvotes: 2
Views: 5667
Reputation: 700362
Don't create the string representation of an object, create an object instead. Also, your loop is wrong, so it would not get the values from the array properly.
var data = {};
for (var i = 0; i < arguments.length; i += 2) {
data[arguments[i]] = arguments[i + 1];
}
Now use the variable in the call:
$.ajax({
type: "GET",
url: "/blog/GetPosts",
data: data,
...
Upvotes: 2
Reputation: 3556
You don't need to pass a query string into data. If you're passing multiple values, you should pass in an object.
$.ajax({
type: "GET",
url: "/blog/GetPosts",
data: {
app: 'blog',
id: 100,
page: 2
pagesize: 10
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {},
error: function (xhr, status, error) {}
});
jQuery will handle the URL encoding for you.
Upvotes: 2
Reputation: 18028
The data: "app=blog&id=100&page=2&pagesize=10"
works and this //data: "{" + args + "}"
doesnt
Because you are using "GET" as request type. to send the data along you need the request to be of type "POST" a GET request can only send the params along with the url.
Upvotes: 0
Reputation: 169401
data: JSON.stringify(someObject)
Store your key/value data in an object then pass the stringified version to data
Upvotes: 1
Reputation: 20371
It sounds like you need to make use of encodeURIComponent
to encode the parameter values that have special characters such as &
, +
or =
. You might also want to check out the comparison between escape(), encodeURI()
and encodeURIComponent()
.
Alternatively, you might make use of $.serialize()
Upvotes: 0