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.

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);
        }
    });
}

I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST.

$sum from $_POST is actually echoed, but not shown in HTML page, but handled as a response back to Ajax.

You have to add a success function in Ajax closure

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

You will see the answer show in page.

php:

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

}
function some_futher_function($param){
    //do some thing
     return $return;
}