【问题标题】:jquery.post does not work with object literaljquery.post 不适用于对象文字
【发布时间】:2012-10-09 01:39:09
【问题描述】:

类似于$.post API 我这样做:

$.post('http://...', POST_BODY, function(data) {...});

POST_BODY                            GIVES ME
{name:'test'}                        Empty response
{'name':'test'}                      Empty response
{"name":"test"}                      Empty response
'{"name":"test"}'                    stdClass Object([name] => test)
JSON.stringify({"name":"test"})      stdClass Object([name] => test)

例如

$.post('http://...', {name:'test'}, function(data) {...});

我的php rest函数:

function postContact(...) {
    $request = Slim::getInstance()->request();
    $body= json_decode($request->getBody());
    print_r($body);
}

为什么我不能使用 jQuery API 中描述的对象字面量?是我的服务器端还是客户端出错了?

【问题讨论】:

  • 如何定义对象?
  • 用“例如...”编辑以使其更清晰

标签: jquery slim


【解决方案1】:

你理解错了。传递对象字面量将导致 jQuery 将对象的每个属性作为键并将所有值转换为字符串并将其转换为具有 key1=val1&key2=val2 形式的 post 参数。当然,这不是 JSON,因此 json_decode 会默默地失败。

【讨论】:

  • 好的,谢谢。我的错误,我认为第二个参数会被转换为 JSON。在文档中很清楚它只是 POST 数据...
【解决方案2】:

jQuery 实际上并没有将“对象文字”发布到您的 PHP 脚本中。它被转换为查询字符串,并作为 POST 数据发送,就像您正常发布表单一样。

你不需要json_decode 任何东西,你只需要读取$_POST 数组,并获取它的值。

您的最后两个示例有效,因为您将 JSON 字符串作为 POST 正文发送,但您的其他示例将标准查询字符串作为 POST 正文发送。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2023-03-29
    • 2021-12-09
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多