如何在没有 html div(id 或 class)的情况下将数据从 Laravel 视图传递到 Ajax 或 Javascript 代码 - Laravel 5.3

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

因此,目前我正在将存储在数据库 MySQL 中的值传递给 View(使用控制器)。我做简单的查询 ModelName::where()->first();.

我现在在 View 中有我的数据。我想在我正在编写的 Ajax 或 Javascript 代码中使用该数据。

我可以有 46 个值,一种方法是让 <div id="field1"></div> 在 css 和 [=] 中将 div 样式设置为 display:none 46 次58=] 使用 document.getElementById('field1'); 访问值,最后,用它做任何我想做的事。

但我发现这样做很长而且没有必要,因为没有必要先打印 html 中的所有值然后再访问它。如何直接在Javascript中获取{{$data}}

我的代码

public function index(Request $request){

        $cattfs = Cattf::all();
        $cattts = Cattt::all();
        $cattos = Catto::all();

        return view('/index',compact('cattfs'));
}

查看

视图中没有任何内容。我更喜欢 none.

Javascript 和 Ajax

$(document).ready(function()
{
    init(); 
});

function init(){
    my_Date = new Date();
    var feedback = $.ajax({
        url:url,
        dataType: "JSON",
        type: "GET",
    }).success(function(data){
   console.log(data);
  //I have some data called data from url
  //I want some data from controller like: cattf,cattt,catto
  //I will combine url data and cattf and do simple arithmetic to it
  //finally output to the view.
  }).responseText;
}

我找到了最好的解决方案:https://github.com/laracasts/PHP-Vars-To-Js-Transformer

它直接从控制器获取值到 Javascript。

一个好方法是实际制作一个小 API 来获取您的数据。假设您想检索用户。

在您的路线文件夹中的 api.php 文件中:

Route::get('/posts', function () {
    return Post::all();
});

然后您只需使用 http://yourUrl.dev/api/posts 作为您在 .ajax() 呼叫中发送的 URL 即可处理您需要的内容。