AJAX / PHP错误处理和全局变量


AJAX / PHP error handling and global variable

这是我第一次写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>

测试.php

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

阿贾克斯返回空白...没有错误,我的error_reporting打开了。

不,这有一些问题:

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

形式.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.';
?>

这是这样做的方法:

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

测试.php

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