简体   繁体   English

将数据库值插入.js文件中

[英]insert db values to a .js file laravel

i have a view, 我有一个看法,

<div class="square_box col-xs-7 text-right">
      <span>Views Today</span>

  <div class="number" id="myTargetElement1"></div>
                            </div>

so i want to pass some values from my database to this .js file the value 90 for instance i want to fetch it from the database 所以我想将一些值从数据库传递到此.js文件,例如,我想从数据库中获取值90

 var demo = new CountUp("myTargetElement1", 12.52, 90, 0, 6, options);
    demo.start();

please help me out cause am stuck trying to figure out how to use the php query script inside a js file found in the public folder 请帮帮我,原因是卡在试图找出如何在公共文件夹中找到的js文件中使用php查询脚本的原因

You've to use AJAX to fetch your data into your JS code and then use it. 您必须使用AJAX将数据提取到JS代码中,然后使用它。

Or you can simply fetch your result from db and pass it to your view. 或者,您可以简单地从db获取结果并将其传递给视图。

$value = DB::table('your_table')->get();
return view('some_view', [ 'value' => $value ]);

Then simply just echo it out using {{ blade }} in your view file 然后,只需在视图文件中使用{{blade}}将其回显即可

<script>
    var demo = new CountUp("myTargetElement1", 12.52, {{ $value }}, 0, 6, options);
</script>

The easiest thing to do would probably be to use ajax to call a view and display that view inside of your html. 最简单的方法可能是使用ajax调用视图并在html内显示该视图。

Here is a very crude example. 这是一个非常粗糙的例子。

$.ajax({
  url: "/path/to/your/view",
  cache: false
})
  .done(function( html ) {
    $( "#myTargetElement1" ).append( html );
  });

I would suggest to use the html tag attribute to store the values and then retrieve it in your JavaScript file. 我建议使用html标记属性存储值,然后在您的JavaScript文件中检索它。
HTML file: HTML档案:

<div class="square_box col-xs-7 text-right">
      <span>Views Today</span>

  <div class="number" data-value={{$value}} id="myTargetElement1"></div>
                            </div>

JS file:. JS档案:。

<script>
    var value = $('#myTargetElement1').attr('data-value');
    var demo = new CountUp("myTargetElement1", 12.52, value, 0, 6, options);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM