首页 > 解决方案 > Laravel 中的 Ajax 无法正常工作

问题描述

我正在尝试在我的 Web 应用程序中实现简单的 Ajax 调用,不幸的是它不起作用。

html代码

<li id="decorative_items">
    Decorative Items
</li>

阿贾克斯代码:

$(document).ready(function() {
var id = 2; /* This has nothing to do with the code */
$("#decorative_items").bind("click", function() {
    alert("click event fired"); /*This is working*/
    $.ajax({
        type:'POST',
        url:'/getDecorativeItems',
        data: {'id' : id},
        success:function(response) {
            alert("foo");
        }
    }); 
});
});

路线/web.php

Route::post('/getDecorativeItems', 'ajaxController@fetchDecorativeItems');

ajaxController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;

class ajaxController extends Controller
{
    function fetchDecorativeItems(Request $request) {
        $msg = "Reached Controller";
        return response()->json(array('msg'=> $msg), 200);
    }
}

我已阅读相关问题的所有答案和其他在线帖子,但我无法找到错误。

注意:代码工作正常,没有语法错误,但我无法达到预期的输出。我正在寻找的预期输出是使用 Ajax 警告“foo”

提前致谢

标签: phpjqueryajaxlaravel-5.6

解决方案


打开你的chrome devtool,检查network -> XHR你的列表XHR request,点击你的ajax request(如果你的 ajax 请求 fase,它有红色)-> 预览看看到底发生了什么,如果你的 Laravel 后端代码有问题,它也会显示在这里。
见下图:

在此处输入图像描述

希望这有帮助,不要通过打印调试alert()


推荐阅读