【问题标题】:ajax not calling controller function laravelajax 没有调用控制器函数 laravel
【发布时间】:2017-08-31 14:22:33
【问题描述】:

我在 javascript 函数中使用以下代码

 $.ajax({
    type: "DELETE",
    url: '/delprofile',
    success:alert("Record deleted."),
        error:  alert("Record not deleted.")
});

我的路线和功能如下:

public function delprofile (Request $request){  
   DB::table('education')->where('id','=',7)->delete();
   return true;
}

Route::post('/delprofile','ProfileController@delprofile');

查询没有执行任何删除操作。

【问题讨论】:

  • 我想应该是Route::delete
  • 我会暂时把路由切换到GET,直接调用URL。或者通过 curl 进行调试。
  • @BjörnTantau 是的,然后它执行删除查询

标签: javascript php jquery ajax laravel-5


【解决方案1】:

由于您的 AJAX 将请求方法设置为 DELETE,因此您必须对路由执行相同操作。

Route::delete('/delprofile','ProfileController@delprofile');

【讨论】:

  • 仍然没有删除
  • 是否调用了正确的控制器方法?你有任何错误吗?
  • 没有错误,我已经给出了所有代码,主要问题控制器方法没有被调用
  • @YusufEkaSayogana 代码现在正在执行,但是 ajax 错误是哎呀,看起来出了点问题。而 delprofile 函数只包含一行:DB::table('education')->where('id','=',7)->delete();
  • @MuhammadMuazzam 打开调试模式老兄,这样你就可以看到错误,而不仅仅是“哎呀”
【解决方案2】:

我认为主要问题来自您的 JS 代码,您错过了 success & error 中的匿名函数:

$.ajax({
    type: "DELETE",
    url: '/delprofile',
    success: function(){ alert("Record deleted.") },
    error:  function(){ alert("Record not deleted.") },
});

或者您也可以改用done/fail

$.ajax({
    type: "DELETE",
    url: '/delprofile',
}).done(function() {
    alert("Record deleted.");
}).fail(function() {
    alert("Record not deleted.");
});

希望这会有所帮助。

【讨论】:

  • 我都试过了,但他们没有删除任何记录。这段代码之后甚至 alert(10) 都没有被执行。
  • 好的,请检查您的浏览器开发工具中的 network/console 选项卡,以确保没有错误并确定请求是否已发送,如果警报在您未执行 ajax 查询后,这意味着您的代码中存在 JS 错误...
【解决方案3】:

在 ajax 代码中添加 CSRF 令牌

data: {'_token': $('meta[name="csrf-token"]').attr('content')
            },

讨论here

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 2018-04-19
    • 1970-01-01
    • 2018-07-27
    • 2014-04-19
    • 2023-03-26
    • 2017-06-06
    • 2014-10-07
    • 1970-01-01
    相关资源
    最近更新 更多