如何将数组传递给ajax帖子?

时间:2015-07-25 16:39:12

标签: javascript jquery ajax

我有这个AJAX帖子脚本:

$.ajax({ 
  url: '/products',
  data: { product[order_id]:order_id, product[product_id]:product_id, product[count]:count },
  type: 'post',
  success: function(result){
     // $('.resultMessage').text(result);
  }
})

它给了我这个错误:Uncaught SyntaxError: Unexpected token [ - 我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

您的数据无效JSON。试试这个:

$.ajax({ 
  url: '/products',
  data: { 
            product: {
                order_id: order_id,
                product_id: product_id,
                count: count
            }
         },
  type: 'post',
  success: function(result){
     // $('.resultMessage').text(result);
  }
})

你可以这样访问它:

var myOrderId = data.product.order_id;

答案 1 :(得分:0)

product_array = // array with key and value pair.

var productString = JSON.stringify(product_array);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : productString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

和php代码如下

$post_data = json_decode(stripslashes($_POST['data']));

// and using foreach you can get key or value as follow.

foreach ($post_data as $key => $value) {
    echo $key;
    echo $value;
}