序列化ajax数组


Serialize an ajax array

我有一个数组从一些输入值得到像这样的jQuery

var ingredient = [];
text.each(function(){
    ingredient.push($(this).val());
});

和ajax发送,像这样

$.ajax({
    url: "update_recipe.php",
    type: "post",
    data: ingredient,
    dataType: "html",
    success : function(code_html, statut){
        console.log(code_html);
        console.log(statut);
    },
    error : function(resultat, statut, erreur){
        console.log("La requête n'a pas aboutie...");
        console.log(resultat);
        console.log(statut);
        console.log(erreur);
    }
    });

但当我需要得到数组与php, $_POST是NULL…
你知道如何发送这个数组吗?

谢谢

您可以创建具有"key=value"对的查询字符串,其中"key"是元素的name属性值,而不是仅将值推入数组。

var ingredient = "";
text.each(function(i) {
    ingredient += this.name + "=" + this.value + (i < text.length ? "&" : "");
});

//使用ajax

//JS

var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
PHP

//

$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array