2015-03-25 60 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); 
       } 
     });