2016-12-29 29 views
1

我想新創建的數據與此調用用ajax

function sendtovenaarData(url){ 
$.ajax({ 

    url: "http://localhost:3000/" + url, 
    type: 'POST', 
    data: 
    { 
     voornaam: $("#voornaam").val(), 
     achternaam: $("#achternaam").val(), 
     beroep: $("#beroep").val(), 
     adres:{ 
      streetAddress: $("#streetAddress").val(), 
      city: $("#city").val(), 
      state: $("#state").val(), 
      zip: $("#zip").val() 
     }, 
     haardplaats: $("#haardplaats").val(), 
     favoriete_quote: $("#favoriete_quote").val() 
    } 

}).done(function() { 

    console.log("data added"); 
    location.reload(); 

}).fail(function (xhr, message, error) { 
    console.log(xhr, message, error); 
});} 

一個我希望將其保存像頂個的圖片,但它節省了張貼到我的JSON數據庫發佈的JSON對象中的對象就像底部的那個反正在那裏呢? image of saved json

我已經嘗試創建一個變量,並將adres放在那裏,但它沒有工作。感謝您的幫助

+0

嘗試使用'JSON.stringify'增加'data'關鍵 –

+0

使用'JSON.stringify()' – Ivan

+0

所以不是任何數據要傳遞的之前將其保存'hello'只要 ? – sandyJoshi

回答

0

顯示您的服務器代碼。如果你使用PHP,那麼你可以嘗試

$data = json_encode($_POST); 

數組轉換成JSON字符串

+0

它完全在JavaScript中完成 – kelig

0

看到這個答案:https://stackoverflow.com/a/5571112/3432422

數據參數應該是一個字符串化的對象,像這樣:

function sendtovenaarData(url){ 
    $.ajax({ 
     url: "http://localhost:3000/" + url, 
     type: 'POST', 
     data: JSON.stringify(
     { 
      voornaam: $("#voornaam").val(), 
      achternaam: $("#achternaam").val(), 
      beroep: $("#beroep").val(), 
      adres:{ 
       streetAddress: $("#streetAddress").val(), 
       city: $("#city").val(), 
       state: $("#state").val(), 
       zip: $("#zip").val() 
      }, 
      haardplaats: $("#haardplaats").val(), 
      favoriete_quote: $("#favoriete_quote").val() 
     }) 
    }).done(function() { 
     console.log("data added"); 
     location.reload(); 
    }).fail(function (xhr, message, error) { 
     console.log(xhr, message, error); 
    });} 
0

我想將它保存爲圖片中的頂部,但它像底部一樣保存,無論如何在這附近?

應指定阿賈克斯頭,是這樣的:

​​

它之後的每個AJAX調用將特定的JSON-頭被髮送。 要發送的數據,你應該做一個:

$.ajax({ 

    url: "http://localhost:3000/" + url, 
    type: 'POST', 
    data: 
    JSON.stringify({ 
     voornaam: $("#voornaam").val(), 
     achternaam: $("#achternaam").val(), 
     beroep: $("#beroep").val(), 
     adres:{ 
      streetAddress: $("#streetAddress").val(), 
      city: $("#city").val(), 
      state: $("#state").val(), 
      zip: $("#zip").val() 
     }, 
     haardplaats: $("#haardplaats").val(), 
     favoriete_quote: $("#favoriete_quote").val() 
    }) 

}).done(function() { 

    console.log("data added"); 
    location.reload(); 

}).fail(function (xhr, message, error) { 
    console.log(xhr, message, error); 
});} 

如果您使用的是後端PHP,這將是不夠的,因爲PHP不能用JSON數據後的工作,和你的$ _ POST將是空的,但如果你正在使用別的東西(java的spring,node js等),它應該正確解析數據。在PHP的情況下,看這裏 - PHP: file_get_contents('php://input') returning string for JSON message

+0

非常感謝你這個偉大的作品 – kelig