Php 如何在通过ajax发布后将值返回到javascript(Jquery)

Php 如何在通过ajax发布后将值返回到javascript(Jquery),php,javascript,jquery,ajax,Php,Javascript,Jquery,Ajax,我通过ajax(jquery)将数据发送到php,并在那里进行处理。我想从php脚本返回一个值,但我不确定如何返回 如何返回结果 $(document).ready(function() { //This script sends var Score to php Score=100; //Dummy variable $.ajax({ type: "POST", url: "returnresul

我通过ajax(jquery)将数据发送到php,并在那里进行处理。我想从php脚本返回一个值,但我不确定如何返回

如何返回结果

$(document).ready(function() {  //This script sends var Score to php
        Score=100; //Dummy variable
            $.ajax({  
            type: "POST",  
            url: "returnresults.php",  
            data: { 'Score':Score },      
            success: function(){  
            $('#box2').html(Score);
            } 
        })
    }); 
非常简单的PHP代码

<?php
$Score=$_POST['Score']; 
       if (isset($_POST['Score'])) { 
       $Score=80;
} 
?>

请检查。特别是关于
success
处理程序函数:

成功(数据、文本状态、jqXHR)

待执行的函数 如果请求成功,则调用。函数通过了三次 参数:从服务器返回的数据,根据 数据类型参数;描述状态的字符串;还有jqXHR (在jQuery1.4.x中,XMLHttpRequest)对象

因此jQuery将向
success
函数传递三个参数。第一个包含您想要的数据。如果您只想将服务器返回的内容准确地传递到
success
处理程序中,您可以执行以下操作:

$(document).ready(function() {  //This script sends var Score to php
        $.ajax({  
        type: "POST",  
        url: "returnresults.php",  
        data: { 'Score':Score },  
        dataType: "text",    //set the dataType to 'text' so that jQuery passes it verbatim
        success: function(newScore){  //the first parameter will contain the response the server sent, we ignore the other two parameters in this example
            $('#box2').html(newScore);
        } 
    })
}); 

然后在PHP代码中,直接将所需的值写入响应

您的PHP页面应该输出您想要返回的html或文本,因此最简单的做法是在PHP的末尾添加以下内容:

$(document).ready(function() {  //This script sends var Score to php
    Score=100; //Dummy variable
        $.ajax({  
        type: "POST",  
        url: "returnresults.php",  
        data: { 'Score':Score },      
        success: function(response){
            alert(response);
            $('#box2').html(Score);
        } 
    })
}); 
echo $Score;
如果要在PHP中对其进行预格式化,请执行以下操作:

echo "<div>" . $Score . "</div>";

谢谢大家的回复!我得躲一会儿,但我今晚一回来就把它们都检查一遍。谢谢!我只是简单地看了一下,但不明白它的重要性。既然你已经指出了这一点,那就完全有道理了。非常感谢。谢谢你的回答。我是一个初学者,所以说我需要什么样的php代码和代表什么样的数据对我有帮助。非常感谢。
$.ajax({  
    type: "POST",  
    url: "returnresults.php",  
    data: { 'Score':Score },      
    success: function(data){ // <-- note the parameter here, not in your code
       $('#box2').html(data);
    } 
});
$('#box2').load("returnresults.php", { 'Score':Score });