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

标签 php jquery ajax post xmlhttprequest

我正在尝试使用 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 注入(inject),但现在,我只想在控制台中使用 .done() 函数打印结果数组。但是,它没有返回任何响应。

有任何想法吗?先感谢您。

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

Picture

最佳答案

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

来自 return manual page :

If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call.



所以return不会产生输出,但会为调用函数的任何内容分配一个值:
function getSomething() {
    return 'something';
}
$something = getSomething();

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

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

其他页面.php:
<?php
return 'hello';

相反,您需要执行以下操作:
echo json_encode($result);

关于PHP:如何从 $.post 请求返回数据作为响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073226/

相关文章:

php - Mac 编程 PHP 时更新不快

php - 按数组变量中值的降序显示结果

javascript - 在MDL中动态添加表单元素

jquery - 如何从 Jquery 的选项标签中删除不显示?

java - 如何使用 Spring Security 将对象从 AJAX 传递到 Spring Controller

php - 我如何检查请求是否通过 CodeIgniter 中的 AJAX 发出?

php - 神秘的 MYSQL 语法错误 - 在 phpMyadmin 中工作正常,而不是在页面上

php - 如何在magento中的店面显示类别?

javascript - 如何向动态构建的表添加 header ?

javascript - 获取 jQuery 表单 - 通过 id 获取文本值