使用 JavaScript 显示 Laravel 的变量 [英] Using JavaScript to display Laravel's Variable

查看:19
本文介绍了使用 JavaScript 显示 Laravel 的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我使用了 typeahead.js.我使用 Laravel 5,我需要用我的 {{ $jobs }} 变量替换 var states.我需要将所有职位列为一个数组.

In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states with my {{ $jobs }} variable. I need to list all Job Titles as an array.

在我的控制器中我有

$jobs = Job::all(['job_title']);

我知道 javascript 中的循环方法,但我不知道如何在 javascript 中链接"我的刀片变量.有人知道怎么做吗?

I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?

我已经尝试过,在 my.js

I have tried, in my.js

var jobs = {{ $jobs }}

但这行不通.

推荐答案

对于更复杂的变量类型(如数组),最好的办法是将其转换为 JSON,在模板中回显并在 JavaScript 中对其进行解码.像这样:

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

<小时>

请注意,PHP 必须运行此代码才能使其工作.在这种情况下,您必须将其放入 Blade 模板中.如果您将 JavaScript 代码保存在一个或多个单独的文件中(这很好!),您只需将内联脚本标记添加到您传递变量的模板中即可.(只要确保它其余的 JavaScript 代码之前运行.通常 document.ready 就是答案)


Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

<script>
    var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>

如果您不喜欢这样做的想法,我建议您在单独的 ajax 请求中获取数据.

If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

这篇关于使用 JavaScript 显示 Laravel 的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆