java - Play 框架中的简单 ajax post 调用

标签 java ajax playframework playframework-2.2

您好,我正在尝试在我的网站上使用 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/

相关文章:

java - 使用简单 XML 和 Gson 库的 REST 客户端 : Use common POJOs or adapter pattern?

java - 使用 Jackcess 读取 Access 文件并使用数据创建 Jtable

javascript - jQuery SubmitHandler 提示加载微调器

ajax - CRUD中的R-功能和披露漏洞之间的界线在哪里?

java - 玩! JPA - 在查询中获取枚举值

java - 使用Java Play发送HTTP请求(WSClient初始化)

java - 数据库 'default' 需要进化!当尝试使用 play Framework 2.7.0 和 Ebean 连接到 MySQL 时

java - 根据 Activity 的 Spring 配置文件提供一个 Maven 依赖项

java - Android 文本框

jquery - Bootstrap 选项卡动态内容