Javascript jQuery 发布请求(非 AJAX)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4583703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:05:16  来源:igfitidea点击:

jQuery post request (not AJAX)

javascriptjqueryasp.net-mvcpost

提问by rem

In an ASP.NET MVC app I use jQuery for posting data on button-click:

在 ASP.NET MVC 应用程序中,我使用 jQuery 在按钮单击时发布数据:

<button onclick="addProducts()">Add products</button>
....
$.post('<%= Url.Action("AddToCart", "Cart") %>',
            {
                ...
                returnUrl: window.location.href
            });

In the "AddToCart" action of "Cart" controller I use redirection to another View after posting:

在“Cart”控制器的“AddToCart”操作中,我在发布后使​​用重定向到另一个视图:

    public RedirectToRouteResult AddToCart(..., string returnUrl)
    {
        ...
        return RedirectToAction("Index", new { returnUrl });            
    }

All is okay, except this redirection. I stay on the same page after posting. I suspect it's due to AJAX type of "POST" request.

一切都好,除了这个重定向。发帖后我留在同一页面上。我怀疑这是由于 AJAX 类型的“POST”请求。

How to solve the problem with jQuery POST request blocking the redirection?

如何解决jQuery POST 请求阻塞重定向的问题?

回答by Facebook Staff are Complicit

I created a $.form(url[, data[, method = 'POST']])function which creates a hidden form, populates it with the specified data and attaches it to the <body>. Here are some examples:

我创建了一个$.form(url[, data[, method = 'POST']])函数,它创建一个隐藏表单,用指定的数据填充它并将其附加到<body>. 这里有些例子:

$.form('/index')

<form action="/index" method="POST"></form>
$.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>
$.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>
$.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>

With jQuery's .submit()method you can create and submit a form with a simple expression:

使用 jQuery 的.submit()方法,您可以使用简单的表达式创建和提交表单:

$.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();

Here's the function definition:

下面是函数定义:

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');
    }
}); });

回答by Horia Dragomir

$.postis an AJAX call.

$.post是一个 AJAX 调用。

Your best bet is to make the button a trigger for a form and just submit that using the post method.

最好的办法是让按钮成为表单的触发器,然后使用 post 方法提交它。

An alternative would be to echo your new url from the server, but that defeats the point of AJAX.

另一种方法是从服务器回显您的新 url,但这违背了 AJAX 的观点。

回答by Victor Haydin

Use jQuery.submit() to submit form: http://api.jquery.com/submit/

使用 jQuery.submit() 提交表单:http: //api.jquery.com/submit/

回答by Brent Anderson

It looks like you are trying to Add Products to the cart and then redirect to your current page. My guess is is that is how you are updating the visual effect of your shopping cart. I would suggest adding the success handler on your $.post and then redirecting to the current page. If an error occurs on the server, you can send back the serialized error and handle it client side.

看起来您正在尝试将产品添加到购物车,然后重定向到您的当前页面。我的猜测是这就是您更新购物车视觉效果的方式。我建议在 $.post 上添加成功处理程序,然后重定向到当前页面。如果服务器发生错误,您可以发回序列化错误并在客户端进行处理。

function addProducts() {
    $.post('<%= Url.Action("AddToCart", "Cart") %>',{
        returnUrl: window.location.href
    }, function(data){
        window.location.href = window.location.href
    });
}

This will refresh your current page after your products are posted.

这将在您的产品发布后刷新您的当前页面。

Here is a fiddle for reference: http://jsfiddle.net/brentmn/B4P6W/3/

这里有一个小提琴供参考:http: //jsfiddle.net/brentmn/B4P6W/3/

回答by DMac the Destroyer

If you're doing a full redirect after a post, then why do it with Ajax? You should be able to perform a tradtional POST here and have it successfully redirect.

如果您在发布帖子后进行完全重定向,那么为什么要使用 Ajax 进行重定向呢?您应该能够在此处执行传统的 POST 并成功重定向。

If you reallywant an ajax request to go through and still redirect, a very easy and non-intrusive way to do that would be to return a JavascriptResultfrom your action instead of a RedirectResult:

如果您真的希望通过 ajax 请求并仍然重定向,那么一种非常简单且非侵入性的方法是JavascriptResult从您的操作中返回 a而不是 a RedirectResult

return JavaScript("window.location = " + returnUrl);