【问题标题】:$_POST not being set with AJAX call$_POST 没有通过 AJAX 调用设置
【发布时间】:2014-02-10 10:22:04
【问题描述】:

这应该是一个相当简单的调用,但我似乎无法让它工作。基本上,我试图将一组搜索参数传递给 PHP 脚本,但 $_POST 是空的。调用(通过 jQuery)...

self.search = function () {
    var data = {
        'year': 2013,
        'month': 10,
        'day': 1
    };

    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: 'repositories/blogposts.php',
        data: { 'search': data },
        success: function(results) {
            // populate knockout vm with results...
        }
    });
};

PHP 代码等待对传入的 json 对象执行某些操作...

if (isset($_POST['search'])) {
    echo find_blogposts(json_decode($_POST['search']));
}

我尝试了很多方法,但无论如何,print_r($_POST) 给了我一个空数组。缺少什么?

【问题讨论】:

  • 试试data: { search: JSON.stringify(data) }

标签: php jquery ajax post


【解决方案1】:

find_blogposts() 内部发生了什么?

您也可以试试.post()

$.post( "repositories/blogposts.php", { year: "2013", month:"10", day:"1" }, function( data ){
  // do something here
});

在您的 php 中,只需接收 $_POST['year'],这将是 2013 年。

希望对你有帮助。

这里是api doc for .post()

【讨论】:

  • 我们甚至没有达到find_blogposts() 的程度,因为$_POST 是空的。不,$.post() 在这里似乎也无能为力。
【解决方案2】:

PHP 可能会阻塞您尝试发送的对象。

您应该直接发送数据对象:

data: data,

(在php中获取$_POST['year']等)

或将对象转换为可以在 php 端解码的 json 字符串:

data: { 'search': JSON.stringify(data) },

【讨论】:

  • 两种方法我都试过了,都不管用。从技术上讲,dataType: 'json' 应该强制对象成为 JSON 字符串。
  • @user1446184 不,dataType: 'json' 指定(并解析...)结果为 json,它与发送到服务器的数据无关。
  • @user1446184 另请注意,由于您已指定要解析为 json 的结果,因此您不能只使用 echoprint_r 任何内容。 find_blogposts() 是否返回有效的 json?检查开发者工具的net 标签,看看你真正得到了什么。
  • 好吧,我设法让它工作了。我确实使用了“JSON.stringify()”调用并显示了结果,即使结果作为有效的 JSON 返回,不管没有它,即使有 PHP 解析错误。必须弄清楚我在电话中做了什么导致这个问题,但到目前为止它似乎已经解决了我的问题。
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
相关资源
最近更新 更多