jquery发布表单和变量在一起

时间:2015-04-29 12:43:04

标签: javascript php jquery

我使用此代码将表单+变量发送到php脚本。

function upload() {
  var test = "test";
  var infos = $('form').serialize() + '&' + test;
  $.post("ajax.php", { infos: infos }).done(function (data) {
    alert(data);
  });
}

现在的PHP代码:

$data = $_POST['infos'];
echo $data;

返回:formfield1 = value1& formfield2 = value2& formfield3 = value3& test

所有值都在此变量中... 但我怎么能用PHP单独使用它们呢?

例如:

$data = $_POST['formfield1'];

无效:(

4 个答案:

答案 0 :(得分:2)

使用jQuery' s serializeArray()。它将返回包含2个属性的对象数组:name和value。然后,您可以解析它并将其作为数据传递。

看起来像这样

var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
    infos[formdata[i].name] = formdata[i].value;
}

// To add separate values, simply add them to the `infos`
infos.newItem = "new value";

$.post("ajax.php", infos).done(function (data) {
    alert(data);
});

然后在PHP中,您将使用$_POST["formfield1"]检索值。

答案 1 :(得分:0)

尝试{ - 1}}使用 -

explode

答案 2 :(得分:0)

您可以使用parse_str方法将查询字符串转换为数组。

在您的情况下,您可以执行以下操作:

parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need

此处有更多详情:http://php.net/manual/en/function.parse-str.php

答案 3 :(得分:0)

//这里是jquery部分

 function upload() {
      var test = "test";
      var infos = $('form').serialize() + '&' + test;
      $.post("ajax.php", { infos: infos },function (data) {
        alert(data); // the fetched values are alerted here.
      });
    }

// php部分在这里

$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
    foreach($form_data_val AS $form_vals){
       $vals=explode($val_seperator,$form_vals);
       echo $vals[1];// here the value fields of every form field and the test is fetched.
    }

试试这个。