Jquery post的对象数组中的字符串数字键

时间:2015-07-16 08:41:54

标签: jquery

我不能将jquery发布为PlainObject:

var ms = {option1: option2}; 

我想要结果:

[227] => 17

但结果是:

[option1] => 17

我该怎么做?如何option1 = "227"作为文本键" 227"?

<script type="text/javascript">
$(".addtocart-button").click(function () {
    var product_id = $(this).attr("id").substring($(this).attr("id").indexOf("-")+1);
    var quantity = $("#qty-" + product_id).val();
    var option1 = $(this).attr("g_opt_id"); //"227"
    var option2 = $(this).attr("p_opt_id"); //"17"


    add_to_cart(product_id, quantity, option1, option2);

    return false;
});

function add_to_cart(product_id, quantity, option1, option2) {
    quantity = typeof(quantity) != 'undefined' ? quantity : 1;

    var cart_path = 'index.php?route=checkout/cart/add'; 
    var ms = {option1: option2}; 
    // i want: [227] => 17, but result: [option1] => 17 
    // How can i do that?

    if (typeof(option1) != 'undefined') {
        pathpost = {"product_id": product_id, "quantity": quantity, "option": ms };
    } else {
        pathpost = 'product_id=' + product_id + '&quantity=' + quantity;
    }

    $.ajax({
        url: cart_path,
        type: 'post',
        data: pathpost,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information, .error').remove();

            if (json['error']) { ...  }    

            if (json['success']) { ... }   
        }
    });
}

1 个答案:

答案 0 :(得分:1)

无论如何,谢谢大家!

    var ms = {}; 
    ms[option1] = option2;