【问题标题】:Submtting data using $.ajax and retrieving values from $_POST array使用 $.ajax 提交数据并从 $_POST 数组中检索值
【发布时间】:2014-07-21 23:23:41
【问题描述】:

我无法检索通过 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");
        }       
    });
});

我可以看到通过网络发送的数据是这样的:

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

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


array (size=0)
  empty

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


第 2 部分:


是的,我之前尝试过 serialize 函数并开始使用 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']; 

我得到空值

不确定这是什么意思?

【问题讨论】:

    标签: php ajax forms serialization


    【解决方案1】:

    您可以简单地使用$(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>
    

    有了这个,您应该使用alert(resp); 收到var_dump($_POST); 的警报

    或者最新的做法,

    <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>
    

    【讨论】:

    • 如果您使用 firefox,我还建议您下载 firebug。它可以让你的生活更轻松。干得好洛兹
    • 感谢您的帮助 - 我将编辑我的问题。
    • 干杯,是的萤火虫或Web Developer
    • 是的,我同时拥有 Firebug 和 Web Developer。上面的 formData 打印输出实际上来自 Web Developer 网络选项卡(这就是我知道正在发送数据的方式)为抬头干杯:IE。
    • @LindaKeating 关于您的编辑,这是来自您的 xdebug 输出(必须是旧的,因为字体标签在 80 年代已被弃用;p),它的 html 不是 XML .. 所以它按预期发回,在php do print_r($_POST['final_approval']); 你看到它会在警报中返回 -1
    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 2012-10-24
    • 2016-02-21
    • 1970-01-01
    • 2013-10-21
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多