使用 jquery 在 POST 请求后重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6624529/
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-26 21:08:46  来源:igfitidea点击:

Redirect after POST request with jquery

jqueryajaxdjangopostredirect

提问by Piero Alberto

I'm working with Django. I have an HTML page, where I do some Javascript stuff, and then I do a jQuery post, in this way:

我正在与 Django 合作。我有一个 HTML 页面,在那里我做一些 Javascript 的东西,然后我做一个 jQuery 帖子,以这种方式:

$.ajax({ 
  url: '/xenopatients/measurement/qual', 
  type: 'POST', 
  data: {'obj':data}, 
  dataType: 'json', 
  contentType: "application/json; charset=utf-8", //questo ok 
}); 

After this post request, my Django view correctly handles the call for this URL. What I want it to do is process the data, send the user to another page, and send this data to the new page. The problem is that I cannot perform the redirect like usual in Python, it's like the code ignores the redirect.

在此发布请求之后,我的 Django 视图正确处理了对该 URL 的调用。我想要它做的是处理数据,将用户发送到另一个页面,然后将此数据发送到新页面。问题是我无法像往常一样在 Python 中执行重定向,就像代码忽略了重定向。

My Python code is:

我的 Python 代码是:

@csrf_protect 
@login_required#(login_url='/xenopatients/login/') 
def qualMeasure(request): 
    name = request.user.username 
    print "enter" 
    if request.method == 'POST': 
        print request.POST 

        if "obj" in request.POST: 
            print 'obj received' 
            return render_to_response('mice/mice_status.html', RequestContext(request)) 

    return render_to_response('measure/qual.html', {'name': name, 'form': QualMeasureForm()}, RequestContext(request)) 

The only way I've found to change the page is through Javascript after the code above:

我发现更改页面的唯一方法是在上面的代码之后通过 Javascript:

top.location.href = "/xenopatients/measurement";

But I don't know how to pass the data I need when using this method.

但是我不知道在使用这种方法时如何传递我需要的数据。

The HTML code:

HTML代码:

<form action="" method=""> 
  <table id="dataTable" width="100%" border="1"></table><br> 
  <script language="javascript"> 
    document.measureForm.id_barcode.focus(); 
    document.measureForm.Add.disabled = false; 
    $('#dataTable').tablePagination({}); 
  </script> 
  <input type="button" name="save" value="Save Measure Serie" onclick="table2JSON('dataTable')"/> 
</form> 

P.S. I've also tried $.post, but with the same results.

PS我也试过$.post,但结果相同。

How can I do a redirect after a post request made with jQuery in Django?

在 Django 中使用 jQuery 发出发布请求后,如何进行重定向?

回答by Piero Alberto

Ok, I've found the magical solution! :)

好的,我找到了神奇的解决方案!:)

The situation: there is a view's method called by jQUery.ajax()

情况:有一个视图的方法被 jQUery.ajax() 调用

To redirect after Ajax, I've used the tips found here(use document instead of 'body' in the jQuery selecotor)

为了在 Ajax 之后重定向,我使用了这里的提示(在 jQuery 选择器中使用文档而不是“body”)

But, I've had also further operations to do.

但是,我还有进一步的操作要做。

in the called view, call another method, like this:

在被调用的视图中,调用另一个方法,如下所示:

[...]
if request.method == 'POST':
    if "obj" in request.POST: #ricevuti dati da ajax
        request.session['qual'] = request.POST['obj']
        return HttpResponseRedirect(reverse("xenopatients.views.qualReport"))

I save the data that I need in the session. I use this data in the called view.

我保存了会话中需要的数据。我在被调用的视图中使用这些数据。

Call another method it's the key for redirect the page of the browser. In fact, at the end of the called method, you can normally write&execute:

调用另一个方法,它是重定向浏览器页面的关键。其实在被调用的方法的最后,可以正常写&执行:

return render_to_response('measure/qualReport.html', {'name':name, 'list_report': report, 'message':'Measures correctly saved'}, RequestContext(request))

Hope this can be useful for someone! ;)

希望这对某人有用!;)

回答by Brandon

@Daniel is correct in that you want to avoid redirects with ajax calls, but you might take a look at this Stack Overflow question which addresses how to do so: How to manage a redirect request after a jQuery Ajax call

@Daniel 是正确的,因为您希望避免使用 ajax 调用进行重定向,但您可以看看这个 Stack Overflow 问题,它解决了如何做到这一点:How to manage a redirect request after a jQuery Ajax call

回答by shah sanket

On button click call this function() below and pass the parameter, in my case I passed new

点击按钮调用下面的这个函数()并传递参数,在我的例子中我传递了新的

function checkforNew(){
                //jQuery.post('<%=request.getContextPath()%>/InspectionController?&oper=new');

                jQuery.ajax({
                    type: "POST",
                    url: '<%=request.getContextPath()%>/MyController?&oper=new',
                    //data: {'obj':data},
                    dataType: "json",
                    success: function(response){
                        window.location.href = response.redirect;
                    }
                });
            }

Inside your servlet you need to mention following code, for the page to redirect.

在您的 servlet 中,您需要提及以下代码,以便重定向页面。

String destination = "/mypage.jsp;

                response.setContentType("application/json");
                JSONObject responsedata = new JSONObject();
                responsedata.put("redirect", destination);

                out.print(responsedata);
                out.flush();