如何将js变量发送到Spring控制器?

时间:2018-02-04 20:12:36

标签: javascript java spring spring-mvc

我有这个HTML代码

<button onclick="var pdata = $('textarea').froalaEditor('html.get');">Submit article</button>

所以我想将此 pdata 变量发送给控制器。我该怎么做呢?或者我应该使用表格吗?

3 个答案:

答案 0 :(得分:2)

如果您已使用jQuery,请考虑使用jQuery.post()方法。

$.post("controller/path", pdata)
    .done(function(response) {
      comsole.log("Response: " + response);
    });

您可以将此代码移动到一个函数,例如,如下所示:

<button onclick="submitArticle()">Submit article</button>

和JS:

function submitArticle() {
    var pdata = $('textarea').froalaEditor('html.get');
    $.post("controller/path", pdata).done(function(response) {
        comsole.log("Response: " + response);
    });
}

请注意,根据jQuery文档,您的pdata应为

  

使用请求发送到服务器的普通对象或字符串。

答案 1 :(得分:0)

嘿,这里是post action ajax + jquery

的工作示例

考虑一个文本字段和一个按钮,例如

myButton的

请参阅以下ajax调用:

function updatData() {
var value= $("#sample").val();
$.ajax({
type : "POST",
url :"url",
data : {id:value},
timeout : 100000,
success : function(response) {
alert(response);   
 },
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
 }
});
}

答案 2 :(得分:0)

$("#button").click(function(){

$.ajax({
type : "POST",
url :"url",
data : {id: $("#field").val()},
timeout : 100000,
success : function(response) {
alert(response);   
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}

});