通过AJAX请求回显某些值不起作用

I've made an ajax call to the test.php and the call is even shown successful in the devtools network. The problem is even after making a successful call the further $country is not been echoed.

这是我的代码

ajax.php

<!DOCTYPE html>
<html>
<head>
    <title>Interval</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
$.ajax({url: 'test.php',
         data: {value: 'India'},
         type: 'post',
         success : function(data){
            alert(data);
         }     
});
</script>
</head>
<body>
</body>
</html>

test.php

<?php
if(isset($_POST['value']) && $_POST['value'] == 'India'){
     $country = $_POST['value'];
        echo $country;
}
?>
评论
听风在唱歌
听风在唱歌

You need to separate your ajax code and call that file from ajax. The reason why this is happening is because ajax.php is returning the whole page output starting from <html> and ending at </html>. So the ajax.php should look like:

<?php
if(isset($_POST['value']) && $_POST['value'] == 'India'){
    $country = $_POST['value'];
    echo $country;
}
?>

然后可以将您的脚本编辑为

<script>
$.ajax({url: 'ajax.php',
    data: {value: 'India'},
    type: 'post',
    success : function(data){
        alert(data);
    }       
});
</script>
点赞
评论