【问题标题】:Why my POST method can't receive this ajax?为什么我的 POST 方法收不到这个 ajax?
【发布时间】:2017-04-07 17:05:12
【问题描述】:

我有这个 javascript 应该将 JSON 发送到我的 escreve POST REST 方法

$(document).ready(function() {
    $("#idform").on('submit', function(e) {
        e.preventDefault();
        alert($("#idform").serialize());
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#idform").serialize() // post data || get data
        })

    });
});

这是我的服务器端escreve 方法:

@POST
@Path("escreve")
@Consumes(MediaType.APPLICATION_JSON)
public void escreve(InputStream dado) throws IOException {
    StringBuilder construtor = new StringBuilder();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(dado));
        String linha = null;
        while ((linha = in.readLine()) != null) {
            construtor.append(linha);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(construtor.toString());
    Pessoa pessoa = gson.fromJson(construtor.toString(), Pessoa.class);
    Repo.escreve(pessoa);       
}

不幸的是,我在 F12 的 Chrome 上收到了这条消息:

jquery.min.js:4 POST http://localhost:8080/DBRest/rest/escreve 415 (Unsupported Media Type)
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous function) @ index.html:20
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3 

使用 js alert($("#idform").serialize()); 我得到了这个:nome=Mary&idade=12 这显然不是 JSON 解析的。我现在我的escreve 方法有效,因为我用一个正确发送 JSON 对象的 java 类对其进行了测试。

【问题讨论】:

  • 所以你有一个接受 json 的方法,你发送的数据你知道 不是 json,你问为什么它不起作用?
  • @f1sh 我在问如何正确地做到这一点。显然,我不仅对最终答案感兴趣。我已经拿到了。如果您有任何其他知识,请提交答案。否则,只需投反对票并等待有人解释。

标签: javascript java jquery json ajax


【解决方案1】:

尝试使用serializeArray,它会创建一个数组。自己测试一下:console.log($("#idform").serializeArray());serialize 创建一个作为 HTTP 请求一部分的查询字符串。从某种意义上说,这两种表示形式是等效的,您可以使用适当的代码将一种表示转换为另一种,而不会产生任何歧义。

这两个版本都可用,因为serialize 如果您想通过将结果放入查询字符串来发出 HTTP 请求很方便,而如果您想自己处理结果,serializeArray 更方便。

【讨论】:

    【解决方案2】:

    尝试单独发送它们

    $.ajax({
                url: 'http://localhost:8080/DBRest/rest/escreve',
                type: 'POST',
                data: { input1: $("#input1").val(), input2: $("#input2").val() },
                success: function(result) {
    
                }
            });
    

    如果你想在 php 中阅读它

    echo $_POST["input1"].$_POST["input2"];
    

    【讨论】:

      【解决方案3】:

      我解决了改变:

      dataType : 'application/json'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-19
        • 2022-01-23
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多