【问题标题】:jquery building array isn't workingjquery 构建数组不起作用
【发布时间】:2013-07-09 04:09:55
【问题描述】:

我正在尝试构建一个数据数组,然后使用 ajax 发布到 php - 下面是我的代码:

$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
    var profilePhotoArray = [];
    $('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
        var action = '';
        alert( this.id );

        if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
            alert('attractive...');
            action = 'attractive';
        }
        else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
            alert('delete...');
            action = 'delete';
        }else{
            alert('normal...');
            action = 'normal';
        }
        profilePhotoArray[this.id+'_'+this.id] = action;
    });

    alert(profilePhotoArray.length);

    for (i=0;i<profilePhotoArray.length;i++) {
        console.log("Key is "+i+" and Value is "+array[i]);
    }


    $.post('scripts/ajax/ajax_approval_functions.php', {
    'approvalProfilePhotos': '1',
    'approvalProfilePhotosData': profilePhotoArray},
    function(data) {
        alert(data);
    });
});

if、else if、else 部分工作正常,因为我可以看到警报。

当我尝试提醒数组长度“profilePhotoArray”时,它显示为 0,所以我没有正确填充数组。我需要使用 .push() 吗?我认为这种格式可以吗?

在通过 ajax 发送到 php 之前,我还需要对数组做任何事情吗?

谢谢

** 编辑 - 我正在添加“profilePhotoArray[this.id+'_'+this.id] = action;” this.id 两次只是为了证明这个词,因为我将传递第二个这样的变量......我最好为此使用 JSON 吗?

【问题讨论】:

  • 一个数组应该由整数索引,但您使用的是字符串 (this.id+'_'+this.id)。
  • 我认为我可以将其用作关联数组...也许我在想很像 PHP...我应该使用索引并将值添加为 JSON 字符串吗?跨度>
  • DevZer0 下面有正确的解释。如果您只是将 profilePhotoArray 更改为对象字面量 (var profilePhotos = {};),您应该已经准备就绪。

标签: php jquery ajax arrays json


【解决方案1】:

Javascript 数组使用数字索引,因此您的存储失败。使用 javascript 对象来存储基于字符串的键。

var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2011-02-12
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多