-1

我只是无法理解它。我需要在我的 php 文件中写什么才能将某些内容返回给$.post函数?

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

这有效,但 PHP 文件没有返回值

4

3 回答 3

1

首先,确保 jQuery 正在访问您的 PHP 文件。使用 Chrome 中的开发人员工具或下载 Firebug for Firefix,转到“网络”选项卡,当您的 JavaScript 函数SubmitToDatabase()执行时,检查以查看任何网络活动。如果它访问错误的 PHP 页面,它将显示 404。

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

于 2013-01-19T15:37:22.250 回答
1
// 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、script、text、html。对于这些格式中的每一种,您必须以合适的方式从后端返回数据。例如text只是echo 'hello!!!; exit;

于 2013-01-19T15:38:22.297 回答
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;
}
于 2013-01-19T15:38:41.860 回答