2015-03-25 57 views
0

我想要發佈一個名稱數組到Web服務。以下是我的代碼寫在JQuery的AJAX:AJAX發佈列表不起作用

var poster=[1,2,3] 
$.ajax({ 
type: "POST", 
traditional:true, 
url:"/post", 
data: {'poster':poster}, 
dataType: 'JSON', 
cache: false, 
success: function(result){console.log(result);} 
}); 

什麼情況是,只有「3」(最後一個數組中的元素)得到公佈。我的console.log也返回Object{poster:"3"}。我嘗試了一切,從添加傳統關鍵字到使數據匿名,如數據:{'':poster}等等。沒有工作。有人可以幫忙嗎?

回答

1

嘗試使用JSON.stringify()

var dataToBePosted = { poster: [1, 2, 3] }; 
$.ajax({ 
    type: "POST", 
    url:"/post", 
    data: JSON.stringify(dataToBePosted), 
    dataType: 'JSON', 
    cache: false, 
    success: function(result){console.log(result);} 
}); 
+0

你讓我的一天。感謝它的作品如此之好 – Tania 2015-03-25 06:58:42

+0

@Tania很高興我可以幫助:) – Yasser 2015-03-25 07:07:44

+0

嗨@亞瑟可以讓你的代碼支持傳遞JSON格式的字符串? – Tania 2015-03-26 04:12:12

1

jQuery將它們變成三個POST參數,如poster[]=1&poster[]=2&poster[]=3。您應該在服務器端收到三個poster[]參數。第一,第二 - 第二和第三 - 3。我想你只是撤回最後一個,所以你只得到3.你需要的是獲得所有人。

+0

我如何獲得所有的人。我的列表也可以擴展 – Tania 2015-03-25 06:53:06

+0

這取決於您在服務器端使用哪種語言和框架。 – 2015-03-25 06:54:43

+0

不。在客戶端,我使用console.log來確定發佈內容。只有最後一個發佈 – Tania 2015-03-25 06:55:33

1

嘗試這樣

var poster=[1,2,3]; 
    $.ajax({ 
      type: "POST", 
      traditional:true, 
      url:"/post", 
      data: {'poster':JSON.stringify(poster)}, 
      dataType: 'JSON', 
      cache: false, 
      success: function(data){ 
      console.log(data); 
      } 
    }); 

 var poster=[1,2,3]; 
     $.ajax({ 
       type: "POST", 
       traditional:true, 
       url:"/post", 
       data: 'poster='+JSON.stringify(poster), 
       dataType: 'JSON', 
       cache: false, 
       success: function(data){ 
       console.log(data); 
       } 
     });