【问题标题】:How to send a correct AJAX JSON?如何发送正确的 AJAX JSON?
【发布时间】:2017-04-07 20:11:05
【问题描述】:

我有一个只有 2 个输入的表单。我想将 JSON 发送到我的 POST 方法。虽然,所有可能性都会返回此错误:

415 (Unsupported Media Type)

我试过用这 3 个 ajax:

        console.log($("#idform").serializeArray());
        console.log($("#idform").serialize());
        var nome = "\"" + $("#idnome").val() + "\"";
        var idade = "\"" + $("#ididade").val() + "\"";
        var all = "{\n"+"\"name\": "+nome+",\n"+
           "\"idade\": "+idade+"\n"+"}";
        console.log(all.toString());
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : all           
        })
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#idform").serializeArray()           
        })
        $.ajax({
            url : 'http://localhost:8080/DBRest/rest/escreve',
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#idform").serialize()          
        })

这是我在控制台上打印后得到的结果:

nome=yrt&idade=09    //$("#idform").serialize()

{
"name": "yrt",       //all
"idade": "09"
}

$("#idform").serializeArray() 返回了[("name","yrt"),("idade","09")]

【问题讨论】:

标签: javascript jquery json ajax


【解决方案1】:

您需要添加以下内容

contentType: 'application/json'

contentType 是您发送到服务器的格式

dataType 是您期望从服务器返回的格式

$.ajax({
  url : 'http://localhost:8080/DBRest/rest/escreve',
  type : "POST", // type of action POST || GET
  contentType : 'application/json', // data type
  data : all           
})

【讨论】:

  • 猜得好,但是你怎么知道服务器在期待什么,OP 没有告诉我们正在使用什么服务器端语言(尽管我猜是 Java)
  • 好点,但确实回答了他的问题,即如何发送正确的 AJAX JSON
  • @Zinc 非常感谢您的耐心等待,这正是我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多