Home  >  Q&A  >  body text

javascript - Can $.ajax({}) be called in js function?

1. I want to do a questionnaire survey. There are multiple questions on the page, and there are multiple options under each question. Finally, there is a submit button to determine whether the user is logged in when submitting. The questions and options are dynamically obtained from the background through $.ajax in the jsp page and displayed in the foreground in html form. Now when submitting, you need to obtain the selected items and questions and store them in the background database for background statistics.

2.form form

<form id="myform" name="myform" method="post">
    <p class="sub730">
        <p class="rightTitleStyle" id="rightTitle">
            <span>有奖调查</span>
        </p>
        <p id="contentp">
            <p class="newsLeftLayoutOp sceneRightLayout">

                <p class="newsDetailContent">
                    <h2>${iyInvestigate.title}</h2>
                    <p class="newsDetailConMsg">
                        <span>发布时间:</span> <span>${iyInvestigate.createTime}</span> <span>活动结束时间:</span>
                        <span>${iyInvestigate.endtime}</span>
                    </p>
                    <p>
                        <span>${iyInvestigate.summary}</span>
                    </p>

                    <p id="optionp" class="test_content_nr"></p>
                    <p class="col-lg-9 col-lg-offset-3">
                            <a id="sub" href="javascript:void(0)" onclick="submitAnswer();">提交</a>
                    </p>
                </p>

            </p>
        </p>
    </p>
</p>
</form>

Dynamic loading of questions and options

    <script type="text/javascript">

    $(document).ready(function(){
      $.ajax({
             type : "post",
             dataType : "json",
             url : "${ctx}/website/yjdc/investigate/findInvestigateOptionByPage.action",
             data : {"id":'${iyInvestigate.id}'},
             success: function(rec){    
                var root = "${ctx}";
                var optionlist = rec.investigateOpList;
                var opHTML = '<ul>';
                for(var i = 0;i<optionlist.length;i++){
                    var option = optionlist[i];
                    
                    opHTML += '<li name="optionTitle" id="qu_0_'+i+'">';
                    opHTML += '<p name="pOptionTitle" class="test_content_nr_tt" id="p_0_'+i+'">'+ option.subject +'</p>';                    

                    opHTML += '<p class="test_content_nr_main">';
                    opHTML += '<ul>';
                    var deoption = option.options;
                    var deoptionsArr = new Array();
                    deoptionsArr = deoption.split("|");   //选项按照|分割开
                    for (var j = 0; j<deoptionsArr.length;j++){
                    
                        opHTML += '<li name="liSelect" class="option">';
                        opHTML += '<input id="0_answer_'+i+'_option_'+j+'" class="radioOrCheck" name="answer'+i+'" type="radio">'+deoptionsArr[j];
                        //opHTML += '<label for="0_answer_'+i+'_option_'+j+'">'+'<p class="ue" style="display: inline;">'+deoptionsArr[j]+'</p>'+'</label>';
                        opHTML += '</li>';
                        
                    }
                    opHTML += '</ul>';
                    opHTML += '</p>';
                    opHTML += '</li>';
                }
                opHTML += '</ul>';
                $('#optionp').html(opHTML);
             }
        })
    });
</script>

Submit function submitAnswer()

function submitAnswer(){
    var userid = "${sessionScope.user.id}";
    if(userid == '')
    {
        alert("未登录,跳转登录页面!");
        var dt = new Date();
        var urlRoot = window.location.pathname;
        var urlParameter = window.location.search;
        var url = urlRoot + urlParameter;
        window.location.href = "${pageContext.request.contextPath}/web/index/toLogin.action?url="+url+"&dt="+dt.getTime();
    } else {
    var k = document.getElementById('sub').innerText;
    var investigateTitle = "${iyInvestigate.title}";
    var indvestigateID = "${iyInvestigate.id}";
   
    //获取同一个主题活动下的题目集合
    var subjectTitleCountObj = document.getElementsByName("pOptionTitle");
    //var optionSelectCount = document.getElementsByName("liSelect").length;
    
    //获取每一道题目以及相应的选项
    for (var k=0;k < subjectTitleCountObj.length;k++){
        //ids = optionTitleCountObj[k].id;
        
        //存储题目
        var subject = $("#p_0_"+ k).text();
        //var val_ = $('input[type="radio"][name="answer'+k+'"]:checked').val();
        
        //存储选中的项
        var selectItem  = "";  
        var radios = document.getElementsByName("answer"+k);
        for (r = 0; r < radios.length;r++) {
            if (radios[r].checked) {
                selectItem = radios[r].nextSibling.data;
            }
        };
        
        
        $.ajax({
            type : "post",
            dataType : "json",
            url : "${ctx}/website/yjdc/investigate/submitAnswer.action",
            data : {"investigateTitle": ${iyInvestigate.title},"investigateID":${iyInvestigate.id},"subjectOp":subject,"selectItemOp":selectItem,"userid":${sessionScope.user.id}},
            success : function(rec)
                        {
                        }
        });
        
//         for (var j=0; j<optionSelectCount;j++){
//             var select = $("#0_answer_"+k+"_option_"+j).text();
//             $("input:radio:checked").val();
//         }
        
        
    }
    }
}
</script>

3. The problem now is that adding $.ajax({}) to function submitAnswer() {} cannot enter the js function submitAnswer at all. Only by removing $.ajax({}) can the submitAnswer function be executed.

Please give me some advice.

伊谢尔伦伊谢尔伦2662 days ago786

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-07-05 10:49:48

    Just add the value under the data parameter in ajax with single quotes, see the following code
    data: {"investigateTitle": '${iyInvestigate.title}',"investigateID":'${iyInvestigate.id} ',"subjectOp":'subject',"selectItemOp":'selectItem',"userid":'${sessionScope.user.id}'},

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:49:48

    Write a console.log to see if the function is entered.


    Furthermore, your way of writing:

    <a id="sub" href="javascript:void(0)" onclick="submitAnswer();">提交</a>
    

    Why bind events in js files:

    html

    <a id="sub" href="#">提交</a>
    

    js

    $('#sub').click(function(){
        submitAnswer();
    });
    

    reply
    0
  • 迷茫

    迷茫2017-07-05 10:49:48

    You can try putting your submitAnswer() in $(document).ready(function(){})

    reply
    0
  • Cancelreply