【问题标题】:AJAX / PHP error handling and global variableAJAX/PHP 错误处理和全局变量
【发布时间】:2015-03-17 16:22:20
【问题描述】:

这是我第一次写ajax 下面是我的结构

提交的.php

<?php $a = $_POST['a'];  // an input submitted from index.php ?>
<button>bind to jquery ajax</button>  // call ajax 
<span></span> // return ajax result here 

<script>
       $('button').on('click', function() {
        event.preventDefault();

        $.ajax({
                  method: "POST",
                  url: "test.php",
                  data: { "key" : 'data'}
                })
                  .done(function( msg ) {
                    $('span').html(msg);
                });
    });
</script>

test.php

<?php echo $a; // will this work? ?>

ajax 返回空白...没有错误,我的 error_reporting 已开启。

【问题讨论】:

  • 我注意到的第一件事是你应该有$_POST['a']而不是$POST_['a']
  • typo...我有大约 10 个输入需要传递给 ajax...有没有办法做到这一点?比如echo $a in data: ?

标签: php jquery ajax


【解决方案1】:

不,这有一些问题:

  • 您正在发布一个键值对,其中键为 key,因此您的 php 脚本中需要 $_POST['key']
  • 如果您需要防止由您的按钮引起的表单提交等事件,您应该使用.preventDefault()。如果是这种情况,您需要从事件处理程序中获取 event 变量:$('button').on('click', function(event) {
    如果没有要阻止的事件,您可以简单地删除该行;
  • 如果您有表单(从您的评论看来是这样),您可以使用以下方式轻松发送所有键值对:data: $('form').serialize()

【讨论】:

  • .serialize() 看起来很有希望,让我看看文档。谢谢。
【解决方案2】:

form.php

<button>bind to jquery ajax</button>  <!-- ajax trigger -->
<span></span> <!-- return ajax result here  -->

<script>

    // NOTE: added event into function argument
    $('button').on('click', function(event) {
         event.preventDefault();

         $.ajax({
             method: "POST",
             url: "test.php",
             data: { "key" : 'data'}
         })
         .done(function(msg) {
             $('span').html(msg);
         });
    });
</script>

进程.php

<?php 

    echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';

?>

【讨论】:

    【解决方案3】:

    这是这样做的方法:

    提交的.php

    <button>bind to jquery ajax</button>  // call ajax 
    <span></span> // return ajax result here 
    
    <script>
           $('button').on('click', function() {
            // no need to prevent default here (there's no default)
            $.ajax({
                      method: "POST",
                      url: "test.php",
                      data: { "key" : 'data'}
                    })
                      .done(function( msg ) {
                        $('span').html(msg);
                    });
        });
    </script>
    

    test.php

    <?php 
       if (isset($_POST['key'])
         echo $_POST['key'];
       else echo 'no data was sent.';
     ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多