PHP和jQuery Ajax没有做任何事情

时间:2015-06-08 18:32:54

标签: javascript php jquery html ajax

我使用AJAX和jQuery在我的主文档中调用PHP函数,创建了一个测试页面(我的第一次PHP测试)。与其他如何完成的答案不同,我的PHP和HTML都在同一个文件中(phptest.php)。当我点击我的按钮提交表单时(这是一个非常简单的测试 - 我点击一个按钮,发生了一些事情 - 我知道我应该使用javascript)我可以在Firebug的面板中看到帖子已发送,我的页面上没有任何反应,所以我认为这是PHP方面的一个问题。有人可以帮助我,或者给我一些关于为什么我的代码不起作用的指示?在这里。

phptest.php

<!DOCTYPE html>
<html>
<head>
    <script src="../jquery/jquery-2.1.4.min.js"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
    <script src="../soundmanager/soundmanager2.js"></script>
    <script src="phptest.js"></script>

    <link rel="stylesheet" type="text/css" href="phptest.css">
    <title>PHP Test | Flippy Coin | thisisatest.com</title>
</head>
<body>
    <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
    <div>
    <?php 
        function wipeCanvas(){}
        function coinFlip(){
            $recentFlip = 0;
            $totalFlips = 0;
            $headsInRow = 0;
            while($headsInRow < 3){
                $recentFlip = rand(0,1);
                if ($recentflip==1){
                    $headsInRow = $headsInRow +1;
                    $totalFlips = $totalFlips +1;
                    echo "<div class=\"coin\">Heads</div>";
                }
                else {
                    $totalFlips = $totalFlips +1;
                    echo "<div class=\"coin\">Tails</div>";
                }
            }
            if ($headsInRow == 3 && $totalFlips <11){
                echo "<p>Hey, we got 3 heads in a row! Wonderful!";

                if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                else {"And it only took us ".$totalFlips." flips!</p>";}
            }
            else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class=\"bold\"> TWENTY-ONE!</p>";}
            else if ($headsInRow == 3 && $totalFlips == 42){
                echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: \" Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!\" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, \"Oh no, not again!\" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
            }
            else if ($headsInRow == 3 && $totalFlips == 420){
                echo "<p>SMOKE WEED EVERYDAY</p>";
            }
            else if ($headsInRow == 3 && $totalFlips < 101){
                echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
            }

            else if ($headsInRow == 3 && $totalFlips < 10000){
                echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
            }
            else if ($headsInRow ==3){
                echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
            } 
        }
        if (isset($_POST['action'])){
            $action = $_POST['action'];
            switch($action) {
                case 'callCoinFlip': coinFlip(); 
                break;
            }
        }
    ?>
    </div>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p>Verdict: <b>PHP is not worth it.</b></p>
</body>
</html>

phptest.js

//   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)

//jQuery 2 Ajax
$(document).ready(function () {
    var data = {'action': 'callCoinFlip'};
    $("#clickMe1").on('click', function(){

        $.ajax({
            type: "POST",
            url: 'phptest.php',
            dataType: "json",
            data: {'action': 'callCoinFlip'},
            success: function(){
                console.log("pootis");
            }
            //error: function(){
                //console.log("Oh no! There has been a problem.");
            //}
        })
    })
})

3 个答案:

答案 0 :(得分:0)

而不是

 success: function(){
            console.log("pootis");
        }

尝试:

 success: function(response){
            console.log(response);
        }

您应该看到服务器响应。但是你永远不会对它做任何事情,你应该在页面上加上类似的东西:

 success: function(response){
            $('body').append(response);
        //    console.log(response);
        }

编辑,说你最终会附加你不需要的东西,如脚本等,可能建议将你的coinflip函数放在一个单独的php文件中

答案 1 :(得分:0)

或试试这个

    

    $(document).ready(function () {
    $('#clickMe1').click(function(e) {
            $.ajax({
            type:'POST', 
            url: 'phptest.php', 
            data: {'action':'callCoinFlip'}, 

                success: function(response) {
                    $('#result').html(response); 
                }
            });
            return false;        
    });
});

答案 2 :(得分:0)

你的代码中犯了两个错误。

  1. coinFlip()函数中,您添加了一个未定义的变量$recentflip。在上面的行中,您声明了一个变量$recentFlip = rand(0,1);。这意味着$recentflip$recentFlip不相等。在PHP中,变量区分大小写。查看reference
  2. 执行post请求后,post函数内的错误函数将被调用而不是成功函数,因为在jquery post函数中添加dataTypejson表示除了php文件将返回一个json字符串。但php文件将返回纯文本。因此,成功函数不会被调用。要了解有关帖子功能中dataType的更多详细信息,请查看此link
  3. 在解决了这两个问题后,我添加了以下代码。

      

    phptest.php

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
        <!--script src="../soundmanager/soundmanager2.js"></script-->
        <script src="phptest.js"></script>
    
        <!--link rel="stylesheet" type="text/css" href="phptest.css"-->
        <title>PHP Test | Flippy Coin | thisisatest.com</title>
    </head>
    <body>
        <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
        <div>
        <?php 
            function wipeCanvas(){}
            function coinFlip(){
                $recentFlip = 0;
                $totalFlips = 0;
                $headsInRow = 0;
                while($headsInRow < 3){
                    $recentFlip = rand(0,1);
                    if ($recentFlip==1){
                        $headsInRow = $headsInRow +1;
                        $totalFlips = $totalFlips +1;
                        echo "<div class=\"coin\">Heads</div>";
                    }
                    else {
                        $totalFlips = $totalFlips +1;
                        echo "<div class=\"coin\">Tails</div>";
                    }
                }
                if ($headsInRow == 3 && $totalFlips <11){
                    echo "<p>Hey, we got 3 heads in a row! Wonderful!";
    
                    if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                    else {"And it only took us ".$totalFlips." flips!</p>";}
                }
                else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class=\"bold\"> TWENTY-ONE!</p>";}
                else if ($headsInRow == 3 && $totalFlips == 42){
                    echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: \" Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!\" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, \"Oh no, not again!\" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
                }
                else if ($headsInRow == 3 && $totalFlips == 420){
                    echo "<p>SMOKE WEED EVERYDAY</p>";
                }
                else if ($headsInRow == 3 && $totalFlips < 101){
                    echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
                }
    
                else if ($headsInRow == 3 && $totalFlips < 10000){
                    echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
                }
                else if ($headsInRow ==3){
                    echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
                } 
            }
            if (isset($_POST['action'])){
                $action = $_POST['action'];
    
                switch($action) {
                    case 'callCoinFlip': coinFlip(); 
                    break;
                }
            }
        ?>
        </div>
        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <p>Verdict: <b>PHP is not worth it.</b></p>
    </body>
    </html>
    
      

    phptest.js

    //   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)
    
    //jQuery 2 Ajax
    $(document).ready(function () {
        var data = {'action': 'callCoinFlip'};
        $("#clickMe1").on('click', function(){
    
            $.ajax({
                type: "POST",
                url: 'phptest.php',
                data: {'action': 'callCoinFlip'},
                success: function(){
                    console.log("pootis");
                }
                //error: function(){
                    //console.log("Oh no! There has been a problem.");
                //}
            })
        })
    })
    
      

    在html页面中显示回复

    我认为在成功执行代码之后,您需要将结果附加到html中。所以我在下面添加了一个代码,将结果附加到html中。 您必须尝试以下代码

      

    phptest.php

    <?php 
        function wipeCanvas(){}
        function coinFlip(){
            $recentFlip = 0;
            $totalFlips = 0;
            $headsInRow = 0;
            while($headsInRow < 3){
                $recentFlip = rand(0,1);
                if ($recentFlip==1){
                    $headsInRow = $headsInRow +1;
                    $totalFlips = $totalFlips +1;
                    echo "<div class=\"coin\">Heads</div>";
                }
                else {
                    $totalFlips = $totalFlips +1;
                    echo "<div class=\"coin\">Tails</div>";
                }
            }
            if ($headsInRow == 3 && $totalFlips <11){
                echo "<p>Hey, we got 3 heads in a row! Wonderful!";
    
                if ($totalFlips ==3){echo "And on our first try, too! ...wait... 3...       </p><p></p><p>HALF LIFE 3 CONFIRMED!</p>";}
                else {"And it only took us ".$totalFlips." flips!</p>";}
            }
            else if ($headsInRow == 3 && $totalFlips == 21){echo "<p class=\"bold\"> TWENTY-ONE!</p>";}
            else if ($headsInRow == 3 && $totalFlips == 42){
                echo "<p> It is important to note that suddenly, and against all probability, a sperm whale had been called into existence, several miles above the surface of an alien planet. And since this is not a naturally tenable position for a whale, this innocent creature had very little time to come to terms with its identity. This is what it thought, as it fell: \" Ahhh! Woooh! What's happening? Who am I? Why am I here? What's my purpose in life? What do I mean by who am I? Okay okay, calm down calm down get a grip now. Ooh, this is an interesting sensation. What is it? Its a sort of tingling in my... well I suppose I better start finding names for things. Lets call it a... tail! Yeah! Tail! And hey, what's this roaring sound, whooshing past what I'm suddenly gonna call my head? Wind! Is that a good name? It'll do. Yeah, this is really exciting. I'm dizzy with anticipation! Or is it the wind? There's an awful lot of that now isn't it? And what's this thing coming toward me very fast? So big and flat and round, it needs a big wide sounding name like 'Ow', 'Ownge', 'Round', 'Ground'! That's it! Ground! Ha! I wonder if it'll be friends with me? Hello, Ground!\" Curiously, the only thing that went through the mind of the bowl of petunias, as it fell, was, \"Oh no, not again!\" Many people have speculated that if we knew exactly *why* the bowl of petunias had thought that we would know a lot more about the nature of the universe than we do now. </p>";
            }
            else if ($headsInRow == 3 && $totalFlips == 420){
                echo "<p>SMOKE WEED EVERYDAY</p>";
            }
            else if ($headsInRow == 3 && $totalFlips < 101){
                echo "<p>Hey, we got 3 heads in a row! It took us ".$totalFlips." flips.</p>";
            }
    
            else if ($headsInRow == 3 && $totalFlips < 10000){
                echo "<p>Okay, so we got 3 heads in a row, but after ".$totalFlips." times?!? That's just not fair!</p>";
            }
            else if ($headsInRow ==3){
                echo "<p>Nope. Nope, nope, nope. ".$totalFlips." flips. Just... no. Honestly, take a screenshot of this and post it on some message board somewhere. How does this happen? I mean, how does a computer take ".$totalFlips." flips before it gets 3 heads? Seriously? This is just... just... I'm done. Don't bother me again. I'M DONE!</p>";
            } 
        }
        if (isset($_POST['action'])){
            $action = $_POST['action'];
    
            switch($action) {
                case 'callCoinFlip': coinFlip(); 
                break;
            }
        }else{
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <!--jQuery 2 script (used for Ajax, titlebar)--> <!--Note: doesn't work with IE 6/7/8-->
        <!--script src="../soundmanager/soundmanager2.js"></script-->
        <script src="phptest.js"></script>
    
        <!--link rel="stylesheet" type="text/css" href="phptest.css"-->
        <title>PHP Test | Flippy Coin | thisisatest.com</title>
    </head>
    <body>
        <button type="button" id="clickMe1">Do Thoust Want to Flip the Coin of Flipping?</button>
        <div id="response">
        </div>
        <p class="verdict">Verdict: <b>PHP is not worth it.</b></p>
    </body>
    </html>
    <?php } ?>
    
      

    phptest.js

    //   onclick="xmlhttp.open(&quot;GET&quot;,&quot;phptest.php?t=&quot;+ Math.random(), true" <-- Just in case ;)
    
    //jQuery 2 Ajax
    $(document).ready(function () {
        var data = {'action': 'callCoinFlip'};
        $("#clickMe1").on('click', function(){
    
            $.ajax({
                type: "POST",
                url: 'phptest.php',
                data: {'action': 'callCoinFlip'},
                success: function(response, status){
                    console.log("pootis");
                    $("#response").html(response);
                    $(".verdict").append("<br/>Accusation:<b id=\"accusation\" style=\"color:red\"><blink>PHP is worth more that what you think. Please improve your skills first.</blink></b>");
    
                    window.setInterval(function() {
                    $('#accusation').toggle();
                    }, 500);
                }
                //error: function(){
                    //console.log("Oh no! There has been a problem.");
                //}
            })
        })
    })