簡體   English   中英

未捕獲的ReferenceError:未定義user_id

[英]Uncaught ReferenceError: user_id is not defined

我需要的

  • 我需要從href調用函數。

HTML代碼

 <a href="#" onclick="peopleattending('.$_COOKIE['user'].', '.$_COOKIE['evnt_id'].');">

js代碼

         <script>

        $(document).ready(function()
        {

            function peopleattending(user_id,event_id)
            {

                console.log(user_id);
                console.log(event_id);

                 $.ajax({
                    type:"GET",
                    url:"{{get_hash_attend(user_id,event_id) }}", 
                     success: function(data)
                     {
                           $("#attend").text("Attending");



                    }
                });

            }

             peopleattending(user_id,event_id);


         });

        </script>

問題

  • 問題未捕獲的ReferenceError:在peopleattending(user_id,event_id)中未定義user_id;
  • 盡管即時獲取值說user_id = 112223和event_id = 9。
  • 如果在url中的函數中傳遞值時出現錯誤:get_hash_attend(user_id,event_id)出現相同的錯誤。

user_idevent_id僅在人員peopleattending功能中定義為參數。 當您這樣調用代碼時:

peopleattending(user_id,event_id);

你基本上是說

peopleattending(undefined,undefined);    

您可以在javascript塊中的pageload上設置變量,而不是在錨標記的函數參考中設置變量

<script>
    var _user_id = '<?php $_COOKIE['user'] ?>';
    var _event_id = '<?php $_COOKIE['evnt_id'] ?>';

    $(document).ready(function()
    {
        function peopleattending(user_id,event_id)
        {
             console.log(_user_id);
             console.log(_event_id);

             $.ajax({
                type:"GET",
                url:"{{get_hash_attend(user_id,event_id) }}", 
                success: function(data)
                {
                       $("#attend").text("Attending");
                }
            });

        }

        peopleattending(_user_id,_event_id);

     });
</script>

然后您的錨標簽看起來像這樣

<a href="#" onclick="peopleattending(_user_id,_event_id);">

對於Symfony:

<script>
    var _user_id = '{% app.request.cookies.get('user') %}';
    var _event_id = '{% app.request.cookies.get('event_id') %}';

我注意到您的問題中有一個錯別字, evnt_id而不是event_id 如果您的代碼中也有此錯字,那么您需要對其進行修復或在javascript中進行更改

如果您的變量是數字而不是字符串,則可以刪除引號

<script>
    var _user_id = {% app.request.cookies.get('user') %};
    var _event_id = {% app.request.cookies.get('event_id') %};

如果您想使用JQuery直接讀取Cookie,則可以使用jQueryCookie插件

<script>
    var _user_id = $.cookie("user");
    var _event_id = $.cookie("event_id");

盡管此時您可以刪除變量,然后在需要的任何地方直接調用$.cookie("user")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM