2012-10-22 22 views
2

我有一个jQuery $.ajax()后,需要添加一个对象(是一个对象?字符串?)到数组中的每个项目的请求。我失去了这样做的最佳方法。我想最好先将数据属性中的项目作为变量分开,以便在请求前计算出来......但我不确定如何构建每个元素。所以这里有些东西是为了说明我的观点。jQuery遍历数组并添加到ajax方法

var items = for (var i = 0; i < $orderItems.length; i++){ 
        'item': { 
         'photo': $orderItems[0].photo, 
         'option': $orderItems[0].option, 
         'cost': $orderItems[0].cost 
        } 
       }, 
    request = $.ajax ({ 
        type: 'POST', 
        dataType: 'json', 
        data: { 
         'firstName': $firstNameVal, 
         'lastName': $lastNameVal, 
         'email': $emailVal, 
         'phone': $numberVal, 
         'address': { 
          'street': $streetVal, 
          'city': $cityVal, 
          'state': $stateVal, 
          'zip': $zipVal 
         }, 
         'price': $orderTotal, 
         'items': items 
        } 
       }); 

回答

2

您可以使用jQuery.map函数来获取项目数组:

var items = $.map($orderItems, function (item) { 
    return { 
      photo: item.photo, 
      option: item.option, 
      cost: item.cost 
    }; 
});