2013-01-19 25 views
-1

我只是无法摆脱困境。我需要在我的php文件中写入什么来返回$.post函数?如何将一个php值返回给jQuery post

<script type="text/javascript"> 
    function SubmitToDatabase(uName, uComment) 
    { 
     $.post("write_something_to_mysql_b.php", {name: uName, comment: uComment}); 
     return false; 
    } 
</script> 

这个工作,但也有从PHP文件

+1

这与PHP无关;这是AJAX请求的异步性质的基本属性; http://stackoverflow.com/questions/562412/return-value-from-function-with-an-ajax-call – Matt

+0

阅读[jQuery.post()](http://api.jquery.com/jQuery .POST /)。有很多实例。 – SeanWM

+1

使用完整的回调...如注意在文档中阅读如何去做 – charlietfl

回答

0
// php: 
$output['result'] = 'hello!!!'; 
echo json_encode($output); // json encode here 
exit; 

// jquery: 
$.post(
"write_something_to_mysql_b.php", 
{ 
    name : uName, 
    comment : uComment 
}, 
function(output) { // callback function to catch your php output 
    // console.debug(output['result']); 
    alert(output['result']); 
    // output hello!!! 
}, 
'json'); // json requirement here 

json只是从后端请求数据的可能性之一。其他是:XML,JSON,脚本,文本,HTML。对于这些格式中的每一种,您都必须以适当的方式从后端返回数据。例如对于text只是echo 'hello!!!; exit;

+0

是的!哇!非常感谢!!! – wubbewubbewubbe

+0

@wubbewubbewubbe不客气。其他答案也是很好的贡献... –

+0

有些东西不能被定期写网页的人猜出。我一直在研究http://api.jquery.com/jQuery.post/数小时。 – wubbewubbewubbe

1

首先,没有返回值,确保jQuery是打你的PHP文件。使用Chrome中的开发者工具或download Firebug进行Firefix,转至“网络”选项卡,并在执行JavaScript函数SubmitToDatabase()时检查网络活动。如果它正在访问错误的PHP页面,它将显示404页。

如果它正在访问正确的 PHP页面,请检查Firebug以查看返回的值。要返回一个JavaScript调用的值,您需要确保您使用的是echo而不是return

+0

+1有关使用萤火虫检查php响应的重要建议 –

1

请参阅jQuery.post()。你必须添加一个成功函数,如果你想用PHP的结果做些什么

function SubmitToDatabase(uName, uComment) 
{ 
    $.post("write_something_to_mysql_b.php", {name: uName, comment: uComment}, 
     function(data) { alert(data); }); 
    return false; 
} 
+0

+1链接到生命的水源:) –