rem*_*rem 37 javascript asp.net-mvc jquery post
在ASP.NET MVC应用程序中,我使用jQuery在按钮单击时发布数据:
<button onclick="addProducts()">Add products</button>
....
$.post('<%= Url.Action("AddToCart", "Cart") %>',
{
...
returnUrl: window.location.href
});
Run Code Online (Sandbox Code Playgroud)
在"Cart"控制器的"AddToCart"操作中,我在发布后使用重定向到另一个View:
public RedirectToRouteResult AddToCart(..., string returnUrl)
{
...
return RedirectToAction("Index", new { returnUrl });
}
Run Code Online (Sandbox Code Playgroud)
一切都没问题,除了这个重定向.发布后我留在同一页面上.我怀疑这是由于AJAX类型的"POST"请求.
如何用jQuery POST请求阻止重定向来解决问题?
小智 95
我创建了一个$.form(url[, data[, method = 'POST']])创建隐藏表单的函数,用指定的数据填充它并将其附加到<body>.这里有些例子:
$.form('/index')
<form action="/index" method="POST"></form>
Run Code Online (Sandbox Code Playgroud)
$.form('/new', { title: 'Hello World', body: 'Foo Bar' })
<form action="/index" method="POST">
<input type="hidden" name="title" value="Hello World" />
<input type="hidden" name="body" value="Foo Bar" />
</form>
Run Code Online (Sandbox Code Playgroud)
$.form('/info', { userIds: [1, 2, 3, 4] }, 'GET')
<form action="/info" method="GET">
<input type="hidden" name="userIds[]" value="1" />
<input type="hidden" name="userIds[]" value="2" />
<input type="hidden" name="userIds[]" value="3" />
<input type="hidden" name="userIds[]" value="4" />
</form>
Run Code Online (Sandbox Code Playgroud)
$.form('/profile', { sender: { first: 'John', last: 'Smith', postIds: null },
receiver: { first: 'Foo', last: 'Bar', postIds: [1, 2] } })
<form action="/profile" method="POST">
<input type="hidden" name="sender[first]" value="John">
<input type="hidden" name="sender[last]" value="Smith">
<input type="hidden" name="receiver[first]" value="John">
<input type="hidden" name="receiver[last]" value="Smith">
<input type="hidden" name="receiver[postIds][]" value="1">
<input type="hidden" name="receiver[postIds][]" value="2">
</form>
Run Code Online (Sandbox Code Playgroud)
使用jQuery的.submit()方法,您可以使用简单的表达式创建和提交表单:
$.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();
Run Code Online (Sandbox Code Playgroud)
这是函数定义:
jQuery(function($) { $.extend({
form: function(url, data, method) {
if (method == null) method = 'POST';
if (data == null) data = {};
var form = $('<form>').attr({
method: method,
action: url
}).css({
display: 'none'
});
var addData = function(name, data) {
if ($.isArray(data)) {
for (var i = 0; i < data.length; i++) {
var value = data[i];
addData(name + '[]', value);
}
} else if (typeof data === 'object') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
addData(name + '[' + key + ']', data[key]);
}
}
} else if (data != null) {
form.append($('<input>').attr({
type: 'hidden',
name: String(name),
value: String(data)
}));
}
};
for (var key in data) {
if (data.hasOwnProperty(key)) {
addData(key, data[key]);
}
}
return form.appendTo('body');
}
}); });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37902 次 |
| 最近记录: |