【问题标题】:PHP: How can I return data as response from $.post request?PHP:如何从 $.post 请求返回数据作为响应?
【发布时间】:2018-12-06 23:11:00
【问题描述】:

我正在尝试使用 jQuery 创建一个简单的 post 函数。输入是客户的姓名,响应是它的信息(地址、电话、年龄等)。到目前为止,我得到了这个:

脚本:

$(document).ready(function(){
    $("#getClientInfo").on('click', function(){
        $.post("getClientInfo.php", {
            name: $('#name').val()
        }) .done(function(data){
            console.log(data);
        }) .fail(function(xhr){
            errorShow(xhr.responseText);
        })
    });

PHP:

$connection = include('dbConnection.php');
$name = $_POST['name'];
$query = mysqli_query($connection, "SELECT * FROM clients WHERE name = 
    $name");
$result = mysqli_fetch_array($query);
return $result;

我知道它非常简单,它不会实现异常或防止 SQL 注入,但现在,我只想在控制台中使用 .done() 函数打印结果数组。但是,它没有返回任何响应。

有什么想法吗?提前谢谢你。

编辑:我希望数组成为请求的响应,因此它显示在 Chrome 中:

Picture

【问题讨论】:

  • 替换return $result;与回声内爆(“,”,$结果);看看这是不是你需要的。
  • @MrGlass 如果你要回答这个问题,请把它放在回答部分。评论用于讨论或要求澄清。

标签: php jquery ajax post xmlhttprequest


【解决方案1】:

你没有从你的 PHP 文件中得到任何输出,因为你的脚本没有产生输出的行。

来自return manual page

如果从全局范围调用,则结束当前脚本文件的执行。如果包含或需要当前脚本文件,则将控制权传递回调用文件。此外,如果包含当前脚本文件,则返回的值将作为包含调用的值返回。

所以return 不会产生输出,但会为调用函数的任何东西赋值:

function getSomething() {
    return 'something';
}
$something = getSomething();

或者将为包含另一个文件的任何内容分配一个值。

index.php:

<?php
$value = include('otherpage.php');
// $value == 'hello'

其他页面.php:

<?php
return 'hello';

相反,您需要执行以下操作:

echo json_encode($result);

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-05-27
    相关资源
    最近更新 更多