【问题标题】:Ajax post request is received as empty objectAjax 发布请求作为空对象接收
【发布时间】:2015-09-18 23:45:02
【问题描述】:

我发送了一个 ajax 发布请求,并得到了响应,但它是空的。是否有一些细节需要调整?

这个想法是发送通过提交按钮提交的文本。但只是为了测试,我已经指定要发送的数据为“url”:“hello”。

$(document).ready(function() {

    $('form.ajax').on('submit', function(e) {
        e.preventDefault();

    var submitted = $(this),
        destination = submitted.attr('action'),
        method = submitted.attr('method'),

        url_send = {
          "url": "helllo"
        };

        $.ajax({
            type: method,
            contentType : 'application/json',
            url: destination,
            data: url_send,
            success: function(response){
                console.log(response);

            },
            error: function(){
                console.log("there was an error");
            }
        });

表格中指定了“方法”(post)和“目的地”。所以“url_send”是发送的对象。这应该在另一端检索为 {"url": "hello"},还是嵌套在对象中?

在带有 laravel 的 PHP 中,我有一个接收请求的控制器函数:

$data = json_decode(file_get_contents("php://input"));

如果 $data 为空,则返回:

return Response::json($data);

这给了我

Object {  }

【问题讨论】:

    标签: php jquery ajax post laravel-4


    【解决方案1】:

    您正在传递data 一个对象,因此它将由jQuery 进行urlencoded。

    urlencoded 数据不是 JSON,因此尝试将其解析为 JSON 将失败。

    您需要实际发送 JSON。

    data: JSON.stringify(url_send)
    

    【讨论】:

    • 我实际上已经尝试过了,但是请求失败并显示错误。我还需要在后端做些什么吗?
    • 现在我明白了,它确实有效,我期待从 php 返回自定义错误消息,但这似乎也导致请求失败。但是,我可以在网络上的浏览器控制台中看到错误消息 - 响应。谢谢你的解释!
    猜你喜欢
    • 2017-03-22
    • 2015-12-10
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2018-11-18
    • 2018-10-24
    • 2018-07-09
    相关资源
    最近更新 更多