PHP 无法获取多个 Ajax 提交数据


php can't get multiple ajax submit data

我有一个表单,它有 2 个提交按钮。

<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
    <input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
    <input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>

我正在使用 Ajax 发送/接收数据。

 $('#posting input[type="submit"]').on("click", function(e) {
   e.preventDefault;
   var btn = $('#publish');
   var el = $(this).attr('id');
   $.ajax({
     type: 'post',
     url: $('form#posting').attr('action'),
     cache: false,
     dataType: 'json',
     data: {
       data: $('form#posting').serialize(),
       action: el
     },
     beforeSend: function() {
       $("#validation-errors").hide().empty();
     },
     success: function(data) {
       if (data.success == false) {
         var arr = data.errors;
         $.each(arr, function(index, value) {
           if (value.length != 0) {
             $("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');

           }
         });
         $("#validation-errors").show();
         btn.button('reset');
       } else {
         $("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto <a href="edit.php">Edit</a>. <div>');
         $('#title').val('');
       }
     },
     error: function(xhr, textStatus, thrownError) {
       alert('Something went to wrong.Please Try again later...');
       btn.button('reset');
     }
   });
   return false;
 });

这是我的PHP文件。 posting_bk.php

if ($_POST['action'] == 'publish') {
         if($title == 'test'){
         array_push($res['errors'], 'data received  by php.');
    }else{
             array_push($res['errors'], 'No data received by php.');
    }
    $res['success'] = true;
    echo json_encode($res);
        }
        elseif ($_POST['action'] == 'save') {
            array_push($res['errors'], 'Save button clicked.');
    $res['success'] = true;
    echo json_encode($res);
    }

一直,如果我点击发布按钮,我就会得到

php 没有收到任何数据

当我签入火虫时,它在 post 下显示数据。喜欢这个

操作发布
data title=test&

不确定我在这里做错了什么。请指教。

将 AJAX 调用更改为使用:

data: $('form#posting').serialize() + '&action=' + el,'

然后使用

$title = $_POST['title'];

按照您这样做的方式,表单数据在POST数据中嵌套了一层,因此您必须执行以下操作:

$data = parse_str($_POST['data']);
$title = $data['title'];