传递键值数组AJAX

时间:2014-03-13 04:59:16

标签: javascript jquery ajax

我有一个键值对数组,我需要通过ajax发送给另一个函数。我的数组看起来像这样

       var vitals=new Array();
       var vitals["height"]=170; 
       var vitals["weight"]=55; 

ajax函数是

     $.ajax({
    type: "POST", //GET or POST or PUT or DELETE verb
    url: url, // Location of the service
    data: JSON.stringify({ccdEntity: vitals }), //Data sent to server
    contentType: "application/json; charset=utf-8", // content type sent to server
    dataType: "json", //Expected data format from server
    processdata: true, //True or False
    success: function (msg) {//On Successfull service call
        ServiceSucceeded(msg);
    }

,接收值的函数是

  public bool GenerateCcd( Array ccdEntity)

当我运行该程序时,该函数不显示具有键值的数组,但是当我传输一个普通数组(即)vitals [0] = 170时,它工作正常。我是否需要对发送上述数据进行更改才能运行?

编辑: 尝试将上述数组作为JSON对象传递

             var vitals= {
        "height": "170",
        "weight": "55"}

但结果仍然相同

2 个答案:

答案 0 :(得分:1)

使用类似这样的东西::

function TestAjax() {
    var vitals= [];

    for (var i = 0; i < 5; i++) {
        vitals.push({ Height: (170+i), Weight: (55+i) });
    }

    $.ajax({
        type: 'POST',
        url: url,
        contentType: "application/json",
        data:JSON.stringify( {vitals: vitals}),
        success: function (data) {
            alert("Succeded");
        }
    });
}

答案 1 :(得分:0)

使vitals成为对象数组而不是数组;;

   var vitals={'height': '170', 'weight': '55'};

并发布您的数据,如:

data: JSON.stringify(vitals)