您好,我正在尝试在我的网站上使用 ajax 按下按钮后,将一个字符串简单地发送到我在 Play 框架中的 java 代码。我找不到简单的教程来简单说明如何执行此操作。他们都在使用模板。 假设我的 java 方法是:
public static Result upload() { }
我的按钮正在调用一个 javascript 方法,该方法在单击时从另一个输入获取字符串:
<input id="submit" type="submit" onclick="send();">
最佳答案
我没有测试,但像这样的东西应该有用。
应用 Controller
public static Result upload() {
JsonNode node = request().body().asJson().get("stringField");
String inputString = node.getTextValue();"
System.out.println(inputString) // prints the string from the form field
return ok();
}
路线
POST /uploadfoostring controllers.Application.upload()
模板
<input type="text" id="string-field">
<input id="submit" type="submit" onclick="send();">
<script type = "text/javascript" >
$('#submit').click(function(evt) {
var inputString = $('#string-field').val();
var obj = {
stringField: inputString;
};
$.ajax({
url: "@routes.Application.upload()",
data: JSON.stringify(obj),
headers: {
'Content-Type': 'application/json'
},
type: 'POST',
success: function(res) {
if (res) {
console.log("Success!");
} else {
console.log("Failed...");
}
}
});
}
</script>
关于java - Play 框架中的简单 ajax post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28288841/