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

Blade视图同目录下JSON文件的JavaScript mounted阶段获取路径咨询

正确加载form.json的路径方案

首先要明确:Blade视图所在的resources/views目录不属于Web服务器的可直接访问路径,直接把form.json放在视图目录下,前端用fetch是拿不到的,你可以通过以下两种方式解决:

方案一:将JSON文件移到public静态目录

Laravel的public目录是Web服务器的根目录,所有静态资源(JS、CSS、JSON等)都应该放在这里:

  • 如果把form.json直接放到public根目录下,fetch路径就是/form.json,你的现有代码可以直接用。
  • 如果想分类存放,比如放到public/forms子目录下,路径就改成/forms/form.json,对应代码:
    mounted(){
      fetch('/forms/form.json')
      .then(res => res.json())
      .then(res => console.log(res))            
      console.log('mounted');
    }
    

方案二:通过Laravel路由返回JSON内容

如果不想移动JSON文件,可通过后端路由读取视图目录里的文件并返回:

  1. 在routes/web.php中添加路由:
    Route::get('/form-data', function () {
        // 替换成你的视图所在具体目录,比如views/home/form.json
        $jsonContent = file_get_contents(resource_path('views/你的视图目录/form.json'));
        return response()->json(json_decode($jsonContent, true));
    });
    
  2. 前端fetch时使用这个路由路径:
    mounted(){
      fetch('/form-data')
      .then(res => res.json())
      .then(res => console.log(res))            
      console.log('mounted');
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:30:54