Redirect after POST request with jquery

后端 未结 3 975
日久生厌
日久生厌 2021-02-01 11:27

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:

$.ajax({ 
  url: \'/xenopatients/meas         


        
相关标签:
3条回答
  • 2021-02-01 11:39

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

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

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

    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! ;)

    0 讨论(0)
  • 2021-02-01 11:39

    @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

    0 讨论(0)
  • 2021-02-01 11:45

    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.

    String destination = "/mypage.jsp;
    
                    response.setContentType("application/json");
                    JSONObject responsedata = new JSONObject();
                    responsedata.put("redirect", destination);
    
                    out.print(responsedata);
                    out.flush();
    
    0 讨论(0)
提交回复
热议问题