【问题标题】:Serialize an ajax array序列化一个ajax数组
【发布时间】:2017-01-25 20:35:22
【问题描述】:

我有一个数组,从一些输入值得到一个像这样的 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...
你知道我该如何发送这个数组吗?

谢谢

【问题讨论】:

  • 显示你的php代码,用console.log检查ingredient的值
  • console.log 的数组类似于 ["2 oeufs", "125 g de farine", "25 cl de lait", "1/2 cuillère à café de sucre", " 1 cc de levure chimique”、“30 g de beurre fonda”、“1/2 cc de sel”、“1 cs d'eau de fleur d'oranger”] 而 php 只是 var_dump($_POST)

标签: php jquery arrays ajax serialization


【解决方案1】:

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

var ingredient = "";

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

【讨论】:

  • 我的 php 脚本似乎没有接收到该字符串。 var_dump($_POST);显示:数组(0){}
  • @Buck 输入元素是否有name 属性?
  • 现在,是的...正确的解决方案是 name="ingredient[]" 谢谢 :)
【解决方案2】:

//使用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

【讨论】:

  • 不需要以 json 格式发送,jQuery 会在内部对数组进行编码
  • 是的,你可以做到
猜你喜欢
  • 2012-12-07
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2016-01-15
  • 2014-12-29
相关资源
最近更新 更多