如何从Laravel 4.2中的视图脚本调用模型的功能

时间:2017-05-05 11:52:20

标签: javascript php ajax laravel laravel-4

我在视图的脚本块中有一个倒数计时器。 Edit.blade.php:

<div class='bottom_timer_block'>
    <span class="bottime_title">Subscription period</span>
    <span><b>End date:</b> {{ $paid_till }}</span>
    <span>
        <b>Countdown timer: </b>
        <span id="demo"></span>
            <script>
                var countDownDate = new Date('{{ $paid_till }}').getTime();                         
                var x = setInterval(function() {
                // Get todays date and time
                var now = new Date().getTime();

                // Find the distance between now an the count down date
                var distance = countDownDate - now;

                // Time calculations for days, hours, minutes and seconds
                var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                // Display the result in the element with id="demo" 
                document.getElementById("demo").innerHTML = days + "d " + hours + "h "
                                    + minutes + "m " + seconds + "s ";

                // If the count down is finished, write some text 
                if (distance < 0) {                                         
                    $.post("/ajax/update-payment", {id:$user->id} ).done(function( data ) {                                                                                           
                    });

                    clearInterval(x);                                           
                    document.getElementById("demo").innerHTML = "EXPIRED";
                }
                }, 1000);
            </script>

当计数器达到它的极限时。它应该调用我的&#34; User&#34;中的updatePayment函数。模型。我的AjaxController:

function updatePayment($id = 0){        
    $user = User::where('id', $id);
    $user->is_paid = 0;
    $user->paid_date = null;
    $user->paid_till = null;
    $user->save();
}

但是我没有得到&#34; Uncaught SyntaxError:Unexpected token&gt;&#34;错误。还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

那是因为你将php变量直接传递给javascript:

{id:$user->id}

然而,另一个问题是花括号在刀片模板引擎中有特殊含义,所以你应该按如下方式传递它:

{id: '{{ $user->id }}' }