繁体   English   中英

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

[英]AJAX / PHP error handling and global variable

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

submitted.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已打开。

不,这有一些问题:

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

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>

process.php

<?php 

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

?>

这是这样做的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM