【问题标题】:Method Not Allowed while doing Ajax执行 Ajax 时不允许使用方法
【发布时间】:2016-03-23 01:45:15
【问题描述】:

路线

Route::put('url/update',['as'=>'test.update', 'uses'=>'TestController@update']);

阿贾克斯

$.ajax({
    url: 'url/update',
    type: 'PUT',
    dataType: 'json',
    data: $inputs ,
    success: function (data, textStatus, xhr) {
        console.log(data);
    },
    error: function (xhr, textStatus, errorThrown) {
        console.log('PUT error.', xhr, textStatus, errorThrown);
    }
});

结果

PUT http://localhost:80/url/update 405 (Method Not Allowed)

【问题讨论】:

  • $device_mac 中是否有空格或非法 URL 字符?
  • 不,里面不应该有空格。为什么我在某个地方有空间?
  • 准确检查您在$.ajax 中获取的网址。
  • 然后,我建议您对 URL 进行console.log() 和/或查看调试器的网络选项卡,并准确查看通过网络发送的请求 URL。
  • Request URL:http://localhost:8888/000D6766F2F6/device/080027E2FC7D 继续切断我的最后 2 段。

标签: jquery ajax


【解决方案1】:

将方法更改为“POST”并在表单中添加一个隐藏元素“_method”,其值设置为“PUT”。

来源:

【讨论】:

  • 好答案,我怀疑这是问题所在。
  • 我同意你的看法。更新我的 POST 路由,更新我的 Ajax type: 'POST',,结果还是一样。
  • 除了这 2 件事之外我还有什么遗漏吗?
  • 如果请求中传递了'_method',你能检查网络日志吗?
  • 我的请求有效负载部分中有_method: "PUT"
【解决方案2】:

HTML 表单仅支持 GET 和 POST,但它确实可以理解真正的 PUT/PATCH 请求。

其他注意事项:
1. 首先使用 Postman 检查您的 API。 1. 确保您的协议是 http / https。
1. 您的 Controller 方法应返回 JSON 格式。
1. 确保您收到您的意见。

有关更多信息,请参阅此答案:
http://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request-

【讨论】:

【解决方案3】:

抱歉,我的评论不正确,因为我对结构的观察不够仔细。我很确定如果修改它会起作用。

我只是设置了以下路线:

Route::put('{cpe_mac}/device/{device_mac}/rate/update', [ 'as'=> 'device.rate.update', 'uses' => 'DeviceController@updateRate']);

我将 javascript 添加到视图中:

$.ajax({
    url: '{{ route('device.rate.update', [$cpe_mac, $device_mac], true) }}',
    type: 'PUT',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: {
        some: 'test'
    },
    success: function(data) {
        console.log(data);
    },
    error: function(xhr) {
        console.log(xhr);
    }
});

我将 true 作为第三个参数传递,因此它构建了一个具有绝对路径的 URL。我认为这比尝试使用env("APP_URL") 更干净。

页面上的结果是:

$.ajax({
    url: 'http://myapp.local/000D6766F2F6/device/080027E2FC7D/rate/update',
    type: 'PUT',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: {
        some: 'test'
    },
    success: function(data) {
        console.log(data);
    },
    error: function(xhr) {
        console.log(xhr);
    }
});

【讨论】:

  • 这很奇怪!它完全符合我的预期,我认为这肯定会对你有所帮助。对不起,祝你好运!
  • 非常感谢您的帮助。
  • 我的 Ajax 现在 POST 成功了,如何在我的控制器中访问?你知道吗?
  • 你想在你的控制器中访问什么?
  • 我使用 Ajax 发布的数据。
猜你喜欢
  • 2012-04-30
  • 1970-01-01
  • 2012-04-11
  • 2017-10-07
  • 2012-06-10
  • 1970-01-01
  • 2020-07-30
  • 2014-03-30
  • 2018-12-15
相关资源
最近更新 更多