2013-09-25 50 views
0
$("#gallery li.gallery-image-item:not(:first)").each(function() {  
    formData.append('gallery[]', {file: 'file', comment: 'comment', youTube: 'youtube'}); 
}); 

我使用formData和XMLHttpRequest将数据从js发送到php。从JS发送数组到PHP?

的问题是上述转储为一个字符串:

string(15) "[object Object]" 

当我依次通过它:

foreach($input['gallery'] as $galleryImg) { 

     var_dump(($galleryImg)); 

} 

我怎样才能访问它作为一个数组?我试过json.stringify和json解码+ json解码,在php方面是true。

没有运气。

+4

这不是你想发送的数组。 –

+0

为什么不是? – panthro

+1

'append()'不是数组上的函数。你有没有尝试发送一个jQuery对象? – Ryan

回答

0

正如@minitech所说,append()不是数组上的函数。如果你想添加项目到你的阵列,你需要使用push()函数。然后你需要将你的数组串化,以便它可以发布到你的PHP。像这样的东西应该工作:

的JavaScript:

var gallery = []; 
$("#gallery li.gallery-image-item:not(:first)").each(function() {  
gallery.push({file: 'file', comment: 'comment', youTube: 'youtube'}); 
}); 

    $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      url: "jsonUrl", 
      data: {gallery : JSON.stringify(gallery)}, 
      success : function(data){ 
       alert(data); 
      } 
     }); 

PHP:

var_dump(json_decode($galleryImg));