PHP和jQuery Ajax没有做任何事情

我做了一个测试页面(我的第一个PHP测试),使用AJAX和jQuery在我的主文档中调用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.");
            //}
        })
    })
})

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

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

    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.");
                //}
            })
        })
    })
    

    代替

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

    尝试:

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

    你应该看到服务器响应。 但是你从来不会做任何事情,你应该在页面上添加如下内容:

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

    编辑,说你会最终追加你不需要的东西,如脚本等,它可能是可取的,把你的coinflip函数在一个单独的PHP文件


    或尝试这一个

        
    
        $(document).ready(function () {
        $('#clickMe1').click(function(e) {
                $.ajax({
                type:'POST', 
                url: 'phptest.php', 
                data: {'action':'callCoinFlip'}, 
    
                    success: function(response) {
                        $('#result').html(response); 
                    }
                });
                return false;        
        });
    });
    
    
    链接地址: http://www.djcxy.com/p/46163.html

    上一篇: PHP and jQuery Ajax not doing anything

    下一篇: Error 415: x