2015-10-16 81 views
0

我想將一個簡單的json字符串傳遞給我的控制器,但它沒有在那裏獲得。我有很多其他字段像插入刪除等在我的控制器代碼,所有這些都將完美工作,除了這個Json接收。我試了很多,但無法找到。我檢查了給定的路徑和它的正確性。是否有任何問題與我的控制器代碼?任何幫助將非常可觀如何將json字符串從jsp頁面發送到Spring mvc控制器

我的JSP代碼

var obj=new Object(); 
    obj.sm=startMonth; 
    obj.sd=startDay; 
    obj.em=endMonth; 
    obj.ed=endDay; 

var jsonDate= JSON.stringify(obj); 

    $.ajax({ 
     type: 'POST',  
     dataType: 'json', 
     url:"/proj/test/dateVerification", 
     data:jsonDate, 

     success: function(jsonDate) {//upto this line from my browser debugger it works 
      if (response == jsonDate) 
      { 
      alert("success and json passed"); 
      } else { 
      alert("not success"+response); 
      } 
     }, 
     error:function(xhr, errorType, exception) { 

      alert("inside error function 1(xhr)"+JSON.stringify(xhr)); 
      alert("inside error function 2(errorType)"+errorType); 
      alert("inside error function 3(exception)"+exception); 
     } 
    }); 

這是我的Spring MVC控制器代碼。

@RequestMapping(value = "dateVerification" , method = RequestMethod.POST) 
    public @ResponseBody String dateVerification(@RequestParam(value="jsonDate",required=true) String jsonDate) { 

     JOptionPane.showMessageDialog(null, jsonDate); 
     System.out.println("JSON Success"+jsonDate);  
     return jsonDate; 
    } 

我無法在我的控制器中打印此Joption和sysout。是否有我的控制器代碼有問題?

任何幫助將非常可觀。

+0

您的RequestParam是字符串,而不是JSONString。 –

+0

我很困惑你的成功回調函數的簽名。 'jsonDate'是在發出ajax請求之前定義的,但它也是成功函數的參數?也許你應該期待回調函數中的響應變量? '成功:功能(反應)'... – Tap

回答

0

這真是一個JavaScript問題。在你的success回調函數中,你接收到一個名爲jsonDate的參數,但是這是一個定義在ajax代碼上面的變量。 response在函數的作用域中未定義,這很可能是您在調試器中看到的錯誤。只需更改回調函數的簽名即可。

success: function(response) { // now response is defined in the scope of the function 
    if (response == jsonDate) 
    { 
     alert("success and json passed"); 
    } else { 
     alert("not success"+response); 
    } 
}, 
相關問題