简体   繁体   English

AJAX函数作用于页面加载,而不是单击按钮

[英]AJAX functions acting on page load rather than button click

This is the first time that I am trying to implement AJAX on a site. 这是我第一次尝试在网站上实现AJAX。 It seems my code runs my AJAX functions on $(document).ready() . 看来我的代码在$(document).ready()上运行了我的AJAX函数。 How can I configure my code to declare these functions without them running when a page has loaded? 加载页面后,如何配置我的代码以声明这些功能而不运行它们?

The code: 编码:

$(document).ready(function(){

    var score = 0; //set result score to start at 0

    $("#start").click( renderNewQuestion()); // get and render a new question when user clicks start
    $("#nextQuestion").click( postResult()); // post result then get and render new question when user clicks next question
    $("#answer-toggle").click( function(){
        $("#question").hide(); //hide question div
        $("#answer").show(); //show answer div
    });
    // omitted code to calculate score as irrelevant

    var newQuestionHTML; //save HTML for new question in a variable

    function getChunk(){
        $.ajax({
            type: 'GET',
            url: '/getchunk/',
            success: function(data) {
                newQuestionHTML = html(data)
            },
            error: function() {
                alert('Something went wrong when getting the next question');
            }
        });
    }

    function renderNewQuestion(){
        getChunk;
        $("review-row").replaceWith(newQuestionHTML);
    }

    function postResult(){
        var result = {
            score: score,
            csrfMiddlewareToken: $("input[name='csrfmiddlewaretoken']").val(),
            chunkID: $("#chunk-id").val(),
        };

        $.ajax({
            type: 'POST',
            url: '/postresult/',
            data: result,
            success: renderNewQuestion(),
            error: function() {
                alert('Something went wrong when posting the results');
            }
        });
    }

});

In this line $("#start").click( renderNewQuestion()); 在此行$("#start").click( renderNewQuestion()); you should pass the function, not execute it, so remove the parenthesis after the function name. 您应该传递函数,而不是执行它,因此请在函数名称后删除括号。

This is a better way to write it BTW: 这是写它的更好的方法:

$("#start").on("click", renderNewQuestion);

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

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