You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中Ajax请求返回字符串而非JSON数据的问题求助

问题原因

你的AJAX请求设置了dataType: "json",但后端路由返回的是纯字符串"blablabla",并非合法JSON格式,导致jQuery解析响应失败,直接进入error回调,因此success里的alert无法触发。另外你前端JS代码存在语法错误:$('#test').click(function(){的函数体缺少闭合的});,这会导致点击事件无法正常绑定。

解决方法

提供两种可行方案,任选其一即可:

方案一:修改前端AJAX的响应类型

将dataType改为"text",让jQuery直接把响应当作文本处理,同时补上缺失的函数闭合括号:

<script>
$('#test').click(function(){
    $.ajax({
        contentType: "application/json",
        dataType: "text",
        url : '/getRequest',
        type : 'GET',
        success: function(response) {       
            alert(response)                 
        },
        error: function(response){console.log(response); }
    });
});
</script>

<button id="test" class="btn btn-secondary" type="button">test</button>

方案二:修改后端返回合法JSON格式

保持前端dataType: "json"不变,将Laravel路由的返回改为JSON格式:

Route::get('/getRequest', function(){
    return response()->json("blablabla");
});

内容的提问来源于stack exchange,提问作者Kentaro Madison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:27:36