将关联数组从ajax发送到php

时间:2015-02-27 12:13:00

标签: php jquery ajax json associative-array

我的查询给出结果query_string和query_string_id我希望该结果为ajax提供数据并将其发送到php

但我不知道 如何通过ajax发送关联数组

请帮我构建我的代码

function querySuccessEnds(tx,results) {
    var len = results.rows.length;
    console.log("DEMO table: " + len + " rows found.");
    var deltaArray=new Array();
    for (var i=0; i<len; i++){
        deltaArray[i]=[];
        deltaArray[i]['query']=results.rows.item(i).query_string
        deltaArray[i]['sync_query_id']=results.rows.item(i).sync_query_id
    }

    var data_to_send = JSON.stringify(deltaArray);
    console.log("data"+data_to_send);
    $.ajax({//to get online data
        type:"POST",
        url:galileoServer + "actions.php",
        data:"get=update&queries="+data_to_send,
        success:function(result){
            console.log(result);
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
        }
    }); //EOC ajax

}// EOC successUpdate

我的php文件

$data = json_decode(stripslashes($_REQUEST['queries']));


foreach($data as $a){
    echo $a->sync_query_id;
    echo $a->query;
}

1 个答案:

答案 0 :(得分:2)

根据发送的数据量,我建议直接使用数据:

$.ajax({
    type:"POST",
    url:galileoServer + "actions.php",
    data:{get:'update',queries:deltaArray},
    success:function(result){
        console.log(result);
    }
});

或使用FormData:

var formdata = new FormData();
formdata.append("get","update");
formdata.append("queries",deltaArray)

$.ajax({
    type:"POST",
    url:galileoServer + "actions.php",
    data:formdata,
    success:function(result){
        console.log(result);
    }
});

ofc这会导致你的php发生变化:

$data = $_REQUEST["queries"];