2013-03-04 111 views
0

在我的jQuery的功能,我使用重定向像window.location.href這樣:如何在jQuery的重定向使用POST而不是GET

window.location.href = "${pageContext.request.contextPath}/redirectUser.ajax?login="+response.result.name; 

它工作正常,但我看到這個字符串在瀏覽器這樣的:

http://localhost:8080/task7/redirectUser.ajax?login=user 

我控制器還使用GET

@RequestMapping (value="/redirectUser.ajax",method = RequestMethod.GET) 
    public String forwardUserToUsersPage(ModelMap model, HttpServletRequest req){ 
     User foundedUser = userDao.findByLogin(req.getParameter("login")); 
     req.getSession().setAttribute("user", foundedUser); 
     return "userPage";//to WEB-INF/jsp/userPage.jsp 
    } 

我怎麼可以重寫應用程序,這部分才能使用r POST方法重定向並在控制器中處理?

下面是從servler收到回覆功能

function doAjaxPost() { 
    // get the form values 
    var queryString = $('#loginform').formSerialize(); 

    $.ajax({ 
    type: "POST", 
    url: "${pageContext. request. contextPath}/loginUser.ajax", 
    data: queryString, 
     //"name=" + name + "&pswd=" + pswd, 

    success: function(response){  
     // we have the response 
     var delay = 1500; 
     if (response.status == "OK_USER") { 
      $('#error').html(''); 
      $('#info').html("Login exists, password is correct everything will be fine.<br> Redirect to User's page"); 

      //var delay = 3000; 
      setTimeout(function() { 
      window.location.href = "${pageContext.request.contextPath}/redirectUser.ajax?login="+response.result.name; 
      }, delay); 

     } 
.... 

所以,我怎麼能重定向使用jQuery或別的東西使用POST方法(功能實際上一部分)?

回答

1

的最快方法我看到:

創建<form>節點,設置它的action正確的URL和method="post",與所需的參數(在<input>字段)填充它,並調用.submit()

例如:

... 
setTimeout(function(){ 
    var $form = $('<form>').attr({ 
     action: "${pageContext.request.contextPath}/redirectUser.ajax", 
     method: "post" 
    }); 

    $form.append('<input name="login" value="'+response.result.name'" />'); 
    $form.submit(); 
}, delay); 
... 
+0

有一種形式,使用jQuery驗證插件進行驗證。該函數從控制器獲取答案,然後將用戶重定向到userPage.jsp或adminPage.jsp。 我通過使用簡單的JavaScript做到了這一點window.location.href 也許在jQuery中有相同的功能? – 2013-03-04 08:50:54

+0

不幸的是,你的解決方案不起作用。 我只是在我的瀏覽器頁身中得到這個字符串: {「status」:「OK_USER」,「result」:{「name」:「user」,「pswd」:「123」}} I've將控制器更改爲POST並添加@ModelAttribute(value =「login」)字符串登錄, 仍然不起作用 – 2013-03-04 09:25:42

+0

在這種情況下,您沒有給出正確的URL來登錄用戶。如果指定'redirectUser.ajax'通過'ajax'進行灌溉並返回以'json'格式化的數據,你應該這樣使用它。看看你的應用程序的邏輯,並檢查用戶應該如何進行身份驗證。 – LeGEC 2013-03-04 09:48:46

相關問題