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

时间:2016-12-07 20:55:51

标签: javascript jquery ajax

这是我第一次尝试在网站上实施AJAX。看来我的代码在$(document).ready()上运行我的AJAX函数。当页面加载时,如何配置我的代码来声明这些函数而不运行它们?

代码:

$(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');
            }
        });
    }

});

1 个答案:

答案 0 :(得分:1)

在这一行$("#start").click( renderNewQuestion());中你应该传递函数,而不是执行它,所以删除函数名后面的括号。

这是写BTW的更好方法:

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