2016-11-23 97 views
0

我有這個JavaScript應該發送JSON我escreve POST REST方法爲什麼我的POST方法不能接收這個Ajax?

$(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方法工作,因爲我測試了一個java類正確地發送一個JSON對象。

+0

所以,你必須接受JSON的方法,你發送的數據是* not * json,你問爲什麼它不起作用? – f1sh

+0

http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – 1252748

+1

@ f1sh我在問如何做到這一點。很明顯,我只對最終答案不感興趣。我已經知道了。如果您有任何其他知識,請提交答案。否則,請立即停止並等待某人解釋它。 – GabrielRado

回答

1

我解決了改變:

dataType : 'application/json' 
0

嘗試使用serializeArray,它創建一個數組。自己測試:console.log($("#idform").serializeArray());serialize創建一個查詢字符串,該字符串意味着成爲HTTP請求的一部分。這兩種表示方式都是等價的,即使用適當的代碼可以將一個代碼轉換爲另一個代碼而沒有任何歧義。

這兩個版本都可用,因爲serialize如果想通過將結果放在查詢字符串中來發出HTTP請求,而serializeArray更方便,如果您想自己處理結果,則可以使用serialize

0

嘗試發送他們sepperatly

$.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"];