为什么我的帖子函数不能访问它上面的变量?

时间:2016-11-04 15:51:36

标签: javascript jquery handlebars.js

我试图弄清楚为什么以下代码末尾的post函数无法访问userID变量(我假设它是一个范围问题,因为在函数返回正确的值之前立即记录userId)

    $.get("/set_languages_user", function(res) {
    console.log(res)

    if ( res.length === 0 ) {

        var getUserInfo = $.get('/set_user', function(res){

            var langConfirmSource = $('#language-confirmation-template').html();
            var langConfirmCompiled = Handlebars.compile(langConfirmSource);
            var langConfirmTemplate = langConfirmCompiled(res)
            $('body').append(langConfirmTemplate)
            $('html').toggleClass('disable_scrolling')

            var userId = res.id
            var native_language = res.native_language
            var learning_language = res.learning_language

            $(document).on('submit', '#language_confirmation', function(e){

                e.preventDefault()

                // prevent user from continuing if they haven't checked that they agree to the term's of use
                if ( $('#touCheck').is(':checked')) {
                    console.log('checked!!!')

                    // this function finds the ID of the User's defined languages
                    var getUserInfo = $.get('/languages.json', function(lang){ 

                        // Find the ID of the languages the User is supporting in order to submit to languages_users db
                        for (i = 0; i < lang.length; i++) {
                            if (lang[i].language === native_language) {
                                var confirmedUserNativeInt = lang[i].id
                            }
                        }

                        for (i = 0; i < lang.length; i++) {
                            if (lang[i].language === learning_language) {
                                var confirmedUserLearningInt = lang[i].id
                            }
                        }

                        console.log(confirmedUserNativeInt)
                        console.log(confirmedUserLearningInt)
                        console.log(userId)


                        // creates a new instance in languages_user for the learningLanguage (level 1)
                        $.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})

                        // creates a new instance in languages_user for the nativelanguage (level 5)
                        $.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })

                        $('.signon_language_confirmation').remove()
                        $('html').toggleClass('disable_scrolling')
                    });

                } else {
                    console.log('not checked!!!')

                    $('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
                }
            })
        });
    }
})

以下是正在呈现的把手模板:

<script id="language-confirmation-template" type="text/x-handlebars-template">
<div class="signon_language_confirmation">

    <p class="title_langconf">Welcome to</p>

    <img src="">
    <div class="wrapper_form_dark language_confirmation_form wrapper_form_sign_on">
        <form id="language_confirmation">
            <div class="form_section">
                <div class="wrapper_input col_16_of_16">
                    <p>I speak {{native_language}} <svg class="icon_standard"><use xlink:href="#{{native_language}}"/></svg></p>
                    <p>I am learning {{learning_language}} <svg class="icon_standard"><use xlink:href="#{{learning_language}}"/></svg></p>

                    <div class="wrapper_tou_signup">
                        <p><input type="checkbox" name="tou" value="agree" id="touCheck"> I agree to Lexody's <a href="#">terms of use</a>.</p>
                    </div>
                    <div class="submit_cancel">
                        <input type="submit" value="Submit" class="btn_primary submit">
                    </div>
                </div> 
            </div>
        </form>
    </div>
</div>

当我提交时,我收到“Uncaught ReferenceError:userId未定义(...)”。如何使这些函数可以访问这些变量,为什么该变量不可访问,但其他变量('confirmedUserLearningInt'和'confirmedUserNativeInt')是?

提前致谢。

1 个答案:

答案 0 :(得分:0)

你还没有在post方法可以达到的地方声明var,正如你在代码中看到的vars在for循环中的if语句中,你应该在for之前声明var这样循环:

&#13;
&#13;
      $.get("/set_languages_user", function(res) {
        console.log(res)
    
        if ( res.length === 0 ) {
    
            var getUserInfo = $.get('/set_user', function(res){
    
                var langConfirmSource = $('#language-confirmation-template').html();
                var langConfirmCompiled = Handlebars.compile(langConfirmSource);
                var langConfirmTemplate = langConfirmCompiled(res)
                $('body').append(langConfirmTemplate)
                $('html').toggleClass('disable_scrolling')
    
                var userId = res.id
                var native_language = res.native_language
                var learning_language = res.learning_language
    
                $(document).on('submit', '#language_confirmation', function(e){
    
                    e.preventDefault()
    
                    // prevent user from continuing if they haven't checked that they agree to the term's of use
                    if ( $('#touCheck').is(':checked')) {
                        console.log('checked!!!')
    
                        // this function finds the ID of the User's defined languages
                        var getUserInfo = $.get('/languages.json', function(lang){ 
    
                            // Find the ID of the languages the User is supporting in order to submit to languages_users db
                            var confirmedUserNativeInt; //<<<<<<<<<<<<<<
                            for (i = 0; i < lang.length; i++) {
                                if (lang[i].language === native_language) {
                                    confirmedUserNativeInt = lang[i].id
                                }
                            }
                            var confirmedUserLearningInt;//<<<<<<<<<<<<<<<<
                            for (i = 0; i < lang.length; i++) {
                                if (lang[i].language === learning_language) {
                                    confirmedUserLearningInt = lang[i].id
                                }
                            }
    
                            console.log(confirmedUserNativeInt)
                            console.log(confirmedUserLearningInt)
                            console.log(userId)
    
    
                            // creates a new instance in languages_user for the learningLanguage (level 1)
                            $.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
    
                            // creates a new instance in languages_user for the nativelanguage (level 5)
                            $.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
    
                            $('.signon_language_confirmation').remove()
                            $('html').toggleClass('disable_scrolling')
                        });
    
                    } else {
                        console.log('not checked!!!')
    
                        $('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
                    }
                })
            });
        }
    })
&#13;
&#13;
&#13;