Reputation: 17095
How is it possible to enable the following JavaScript function, sending a POST request, to recieve productID
parameter not as a single string variable but as a collection of productID
's?
i.e. to get in output a string like:
"productId=126504&productId=126505&productId=126506&productId=126507&productId=126508"
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function addToCart(productId, returnUrl) {
var form = $(document.createElement('form'))
.attr('action', '/products/addtocart')
.attr('method', 'post')
.append(
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'productId')
.val(productId)
)
.append(
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'returnUrl')
.val(returnUrl)
);
$('body').append(form);
form.submit();
}
</script>
Edit:
Just to be more clear: When calling this function with a parameter 126504 the function outputs productId=126504. How to pass multiple productID's 126504,126505,126506,126507,126508 in order to get the function output 126504&productId=126505&productId=126506&productId=126507&productId=126508 ?
I call the function from a Silverlight app:
HtmlPage.Window.Invoke("addToCart", "126504", "http://localhost:10930/Products");
Upvotes: 0
Views: 793
Reputation: 17095
Sorry if my question was a little unclear. Here it is a variant of the function, I've managed to start working as I wanted:
function addToCart3(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var i = 0, l = params.length; i < l; i++ ) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "productId");
hiddenField.setAttribute("value", params[i]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}
If passing to this function an array of string, the server gets the data as required
string[] arrstrpostdata = new string[] { "126504", "126505", "126506", "126507", "126508", "126509" };
HtmlPage.Window.Invoke("addToCart3", "http://localhost:10930/Cart/AddCollToCart", arrstrpostdata);
Upvotes: 0
Reputation: 2170
Add multiple input items with the same name on the same form, and you should get exactly what you're looking for.
Upvotes: 3