Ajax post请求作为空对象接收


Ajax post request is received as empty object

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

其想法是发送通过提交按钮提交的文本。但为了测试,我指定了要发送的数据为"url":"helllo"。

$(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":"helllo"}的形式检索,还是嵌套在对象中?

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

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

如果$data为空,则返回:

return Response::json($data);

这给了我

Object {  }

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

url编码的数据不是JSON,所以尝试将其解析为JSON将失败。

您需要实际发送JSON。

data: JSON.stringify(url_send)