weixin_33698823 2015-06-15 06:11 采纳率: 0%
浏览 8

Ajax测试不起作用

I tried to get a simple ajax-test working but without success. I am trying to pass a variable($add1) from PHP to JS, then let the JS calculate the sum and return it back to a PHP variable via $_POST and ECHO it out in the html.

index.php:

<?php 

echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum($add1)</script>";
$sum = $_POST['variable'];

echo $sum;

?>

script.js:

function sum(param) {
    var sum = 3;
    sum = 3 + param;

    $.ajax({
        type: 'POST',
        url: 'index.php',
        data: {
            'variable': sum
        },
    });
}

For some reason this code doesn't work. Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • weixin_33739541 2015-06-15 06:19
    关注

    Include this on your page before your script.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    

    PHP code

    <?php 
    
    if ($_POST['variable']) { // If ajax request only
        $sum = $_POST['variable'] + $add1;
        echo $sum;
    } else { // Loading in the browser
        $add1 = 3;
        echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="script.js"></script>';
    
        echo "<script>sum(".$add1.")</script>";
    }
    ?>
    

    Javascript

    function sum(param) {
        var sum = 3;
        sum = 3 + param;
    
        $.ajax({
            type: 'POST',
            url: 'index.php',
            data: {
                'variable': sum
            },
            success: function(result) {
                alert(result)
            },
            error: function(e) {
                console.log(e);
            }
        });
    }
    
    评论

报告相同问题?