【问题标题】:PHP function not returning any data to JQuery ajax methodPHP函数没有向JQuery ajax方法返回任何数据
【发布时间】:2011-08-30 19:34:08
【问题描述】:

我正在使用 jquery 的 ajax 方法将一些数据发布到服务器并取回响应。虽然服务器端 php 代码返回一个 json 编码的字符串/数组,但响应返回为 null。

有人能指出我犯的错误吗?下面如果我使用我的 jquery ajax 方法来访问 postData.php 页面。

        $.ajax({
            url:'postData.php',
            type:'POST',
            data:data,
            dataType: "json",
            success: function(response){
                console.log(response);
            }
        });

postData.php 中的内容非常简单,因为我仍在开发它。

    $data = array();
//inside postData.php
    $data['test']=1;
    return json_encode($data);

它应该返回一个 json 字符串,但它返回的是 null。我还尝试在 $data 数组声明之后回显一个字符串,它确实在萤火虫中回显它,但响应是当我在成功回调上执行 console.log 时,它返回为 null。

【问题讨论】:

    标签: ajax jquery return jquery-post


    【解决方案1】:

    这就是 postData.php 中的全部内容吗?您需要在某个时候将其写入缓冲区 (echo json_encode($data);)。

    【讨论】:

    • 谢谢!! jquery 和 ajax 用了好久,急于把事情搞定,就犯了这个可笑的错误!!
    【解决方案2】:

    为了在你的 ajax 函数中返回结果,你必须回显它,而不是返回,比如:

    $data = array();
    $data['test']=1;
    echo json_encode($data);
    

    【讨论】:

    • 谢谢!! jquery 和 ajax 用了好久,急于把事情搞定,就犯了这个可笑的错误!!
    【解决方案3】:

    就像 morgar 指出的那样,您应该回显数据而不是使用 return。

    $data = array();
    $data['test']=1;
    echo json_encode($data); //echo instead of return
    

    同时,在您的 ajax on success 函数中,您应该像访问数组一样访问响应。

    **Incorrect**
    console.log(response); //--> would return an error
    
    **Should Be**
    console.log(response[0]); //--> read the returned first array element
    

    【讨论】:

    • 为什么会出错?他只是在 console.log()'ing 一个数组。
    • @John Green - PageSpike :嗯,我认为这会导致错误,因为如果他在数组中有 2 个元素,要获得值,它将是 response[0] 和 response[1] ?我错了吗?
    • 一般称为稀疏数组。这样做是合法的。
    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多