使用$ .ajax提交数据并从$ _POST数组中检索值

时间:2014-06-01 21:01:54

标签: php ajax forms serialization

我无法检索我的表单数据已通过ajax提交,如下所示:

$( "form" ).on( "submit", function( event ) {
    var formData = $(this).serializeArray();
    console.log("fomData");
    $.ajax({
        url: window.location.origin+ "/selfservicemanager/localtmfsetup/local_tmf_setup.php",
        type: "POST",
        data: JSON.stringify(formData),
        success : function (){
            alert("success");
        }       
    });
});

我可以看到通过网络发送的数据如下: enter image description here

但是当我尝试在服务器端检索数据时,$ _POST数组为空。

<?php
var_dump($_POST);
die();
?>


array (size=0)
  empty

有什么想法吗?我试图对发送的数据进行字符串化,并尝试解码$ _POST数组,但它需要一个字符串.....


第2部分:


是的,我之前尝试过序列化函数,并开始使用serializeArray()函数,看它是否可行。我尝试使用jquery的$ .post()而不是$ .ajax() - 但似乎没有任何效果。但是,我现在认为这是一个Chrome问题。我刚刚在Firefox上测试过,一切正常。我还查看了在chrome调试器中返回的响应,有趣的是,它正在将$ _POST数组打印为XML,如下所示:

 <pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=7)</i>
  'weekly_out_of_office' <font color='#888a85'>=&gt;</font> 
    <b>array</b> <i>(size=3)</i>
      0 <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'monday'</font> <i>(length=6)</i>
      1 <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'wednesday'</font> <i>(length=9)</i>
      2 <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'friday'</font> <i>(length=6)</i>
  'public_holiday_names' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
  'public_holiday_value' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'6/17/2014'</font> <i>(length=9)</i>
  'pay_day' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'1'</font> <i>(length=1)</i>
  'final_approval' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'-1'</font> <i>(length=2)</i>
  'final_output' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'-6'</font> <i>(length=2)</i>
  'file_input_type_1' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'fdsff'</font> <i>(length=5)</i>
</pre>

但是当我尝试通过PHP访问这些值时,如

$final_approval = $_POST['final_approval']; 

我得到了空

不确定这意味着什么?

1 个答案:

答案 0 :(得分:2)

您可以简单地使用$(this).serialize(),也可以不像您想象的那样通过网络发送,因为您在发送之前写入控制台,所以它看起来就像是。

试试这个:

<script>
$( "form" ).submit(function(event){
    $.ajax({
        url: window.location.origin+ "/selfservicemanager/localtmfsetup/local_tmf_setup.php",
        type: "POST",
        data: $(this).serialize(),
        success : function (resp){
            alert(resp);
        }       
    });
    event.preventDefault();
});
</script>

有了这个,您应该使用var_dump($_POST);

收到alert(resp);的提醒

或者最新的做法,

<script>
$( "form" ).submit(function(event){

    var request = $.ajax({
        url: window.location.origin+ "/selfservicemanager/localtmfsetup/local_tmf_setup.php",
        type: "POST",
        data: $(this).serialize()
    });
    request.done(function( resp ) {
        alert(resp);
    });
    request.fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });

    event.preventDefault();
});
</script>

另请注意,IE中不支持window.location.origin,因此在引导JS时需要添加以下内容

/* IE Fix for .origin  */
if(!window.location.origin) {
    window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port?':'+window.location.port:'');
}

更新(简单示例)

<?php 
/* check POST */
if($_SERVER['REQUEST_METHOD'] == 'POST'){

    /* do std form handling ect */
    $value = isset($_POST['value']) ? $_POST['value'] : null;

    //do the rest of logic ect
    //..

    /* Then finally respond with json if request from AJAX -
        this way you can handle javascript on and off browsers.
     */
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        //setup to respond with
        header('Content-Type: application/json');
        //send back - example
        exit(json_encode(array('value_from_ajax' => $value)));
    }
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
jQuery(document).ready(function(){
    $(".input_form").submit(function(event){

        var request = $.ajax({
            //url: window.location.origin+ "/selfservicemanager/localtmfsetup/local_tmf_setup.php",
            url: window.location.origin+ "/ajax_test.php", // <--!
            type: "POST",
            data: $(this).serialize(),
            dataType: "json"
        });
        request.done(function( resp ) {
            $("#ajax_resp").html(resp.value_from_ajax);
        });
        request.fail(function( jqXHR, textStatus ) {
            alert( "Request failed: " + textStatus );
        });

        event.preventDefault();
    });
});
</script>
</head>

<body>

<h1>Example</h1>
<form method="post" action="" class="input_form">
    <fieldset> 
        <legend>Da form</legend>

        <label>Value :</label>
        <input type="text" name="value" value="" required>

        <input type="submit" value="Submit">
    </fieldset>
</form>
<p id="ajax_resp"></p>

</body>
</html>