【问题标题】:How to send json String from jsp page to Spring mvc controller如何将json字符串从jsp页面发送到Spring mvc控制器
【发布时间】:2015-10-16 08:35:11
【问题描述】:

我正在尝试将一个简单的 json 字符串传递给我的控制器,但它没有到达那里。我有很多其他字段,例如在我的控制器代码中插入删除等,所有这些都可以正常工作,除了这个 Json接收。我尝试了很多,但无法找到。我检查了给出的路径及其正确性。我的控制器代码有什么问题吗?任何帮助都将非常感激

我的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。我的控制器代码有什么问题吗?

任何帮助都将不胜感激。

【问题讨论】:

  • 您的 RequestParam 是字符串,而不是 JSONString。
  • 我对你的成功回调函数的签名感到困惑。 jsonDate是在发出ajax请求之前定义的,但它也是成功函数的参数?也许您应该期待回调函数中的响应变量? success: function(response)...

标签: javascript jquery json spring jsp


【解决方案1】:

这确实是一个 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);
    }
},

【讨论】:

    最近更新 更多