Javascript jquery将表单和变量发布在一起

Javascript jquery将表单和变量发布在一起,javascript,php,jquery,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

我使用这段代码将表单+变量发送到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'];
未工作:(

使用jQuery。它将返回包含两个属性的对象数组:名称和值。然后您可以解析它并将其作为数据传递

它可能看起来像这样

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);
});
var formdata==$('form').serializeArray();
var-infos={};
对于(var i=0;i

然后在PHP中,您将使用
$\u POST[“formfield1”]
检索值,尝试使用
分解它们-

$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();

foreach ($form_data as $value) {
    list($key, $val) = explode('=', $value);
    $posted_data[$key] = $val;
}

var_dump($posted_data);

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

在您的情况下,您可以这样做:

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

更多详细信息:这里是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.
    }

试试这个。

只需将它们添加到infos对象
infos.testItem=“test”