【问题标题】:Simple ajax post call in Play frameworkPlay框架中的简单ajax post调用
【发布时间】:2015-04-02 01:18:17
【问题描述】:

您好,我正在尝试在我的网站中使用 ajax 在 Play 框架中的 java 代码中按下按钮后简单地发送一个字符串。我找不到一个简单的教程来简单地解释如何做到这一点。他们都在使用模板。 假设我的 java 方法是:

  public static Result upload() { }

我的按钮正在调用一个 javascript 方法,该方法在单击时从另一个输入中获取一个字符串:

<input id="submit" type="submit" onclick="send();">

【问题讨论】:

    标签: java ajax playframework playframework-2.2


    【解决方案1】:

    我没有测试,但这样的东西应该可以工作。

    应用程序控制器

    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>
    

    【讨论】:

    • @Diego,是的,谢谢。中途换了个名字。我进行了编辑。
    • 我在这条线上遇到了 Nullpointer 异常JsonNode node = request().body().asJson().get("stringField");
    • 我也想发送我的输入文件。目前我的表单对 /upload 有一个发送多部分的操作。这是ajax没有工作的原因吗?
    【解决方案2】:
    POST        /home/testPost                               controllers.Application.testPost
    
    //Server Side.
    def testPost = Action { request =>
    
        println("testPost Called");
        println(request.body.asFormUrlEncoded.get("name").head);
        Ok("Succeeded");
    
    }
    
    
    Client Side:
    
    public static testPost(){
    $.ajax({
    url:"/dialog/testPost",
    type:"POST",
    data:{
    name:"Varadharajan R"
    },
    success:function(response){
    alert(response);
    }
    });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 2011-07-15
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2016-05-29
      • 2013-03-06
      • 2020-04-26
      相关资源
      最近更新 更多