PHP:如何从$ .post请求返回数据作为响应?

问题描述 投票:1回答:1

我正在尝试使用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

php jquery ajax post xmlhttprequest
1个回答
0
投票

您没有从PHP文件中获取任何输出,因为您的脚本没有生成输出的行。

来自return manual page

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

因此return不会产生输出,但会为调用函数的任何内容赋值:

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

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

index.php文件:

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

otherpage.php:

<?php
return 'hello';

相反,你需要做类似的事情:

echo json_encode($result);
© www.soinside.com 2019 - 2024. All rights reserved.