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

查看:133
本文介绍了使用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天全站免登陆