消息关闭
    暂无新消息!

$.ajax({}) 能否在js函数中调用?

问题作者 : Monica2017-06-05发布

1.想做一个问卷调查。 页面中有多个题目,每个题目下有多个选项,最后有一个提交按钮,提交时判断用户是否登录。题目和选项都是在jsp页面中通过$.ajax从后台动态获取以html形式显示在前台。 现在提交时需要获取选择的项和题目将其存入后台的数据库中,以便后台统计。

2.form表单

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

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

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

            </div>
        </div>
    </div>
</div>
</form>

动态加载题目和选项

    <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 += '<div name="divOptionTitle" class="test_content_nr_tt" id="div_0_'+i+'">'+ option.subject +'</div>';                    

                    opHTML += '<div 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 += '</div>';
                    opHTML += '</li>';
                }
                opHTML += '</ul>';
                $('#optionDIV').html(opHTML);
             }
        })
    });
</script>

提交函数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("divOptionTitle");
    //var optionSelectCount = document.getElementsByName("liSelect").length;
    
    //获取每一道题目以及相应的选项
    for (var k=0;k < subjectTitleCountObj.length;k++){
        //ids = optionTitleCountObj[k].id;
        
        //存储题目
        var subject = $("#div_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.现在的问题是在 function submitAnswer() {} 中加$.ajax({})根本进不了js函数submitAnswer。 去掉$.ajax({})才可以执行submitAnswer函数。

请各位大神指教。


3个回答

︿ 0

写个 console.log 看看函数到底有没有进去。


再者,你这个写法:

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

为什么在 js 文件中绑定事件呢:

html

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

js

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

整个页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/website/INCLUDE/common.jsp"%>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="${ctx}/website/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<link href="${ctx}/website/css/style.css" rel="stylesheet" type="text/css">
</head>

<body style="background:#f2f2f2;">
    <div class="box1003">
    <form id="myform" name="myform" method="post">
        <div class="sub730">
            <div class="rightTitleStyle" id="rightTitle">
                <span>有奖调查</span>
            </div>
            <div id="contentDIV">
                <div class="newsLeftLayoutOp sceneRightLayout">
                    <div class="newsDetailContent">
                        <h2>${iyInvestigate.title}</h2>
                        <div class="newsDetailConMsg">
                            <span>发布时间:</span> <span>${iyInvestigate.createTime}</span> <span>活动结束时间:</span>
                            <span>${iyInvestigate.endtime}</span>
                        </div>
                        <div>
                            <span>${iyInvestigate.summary}</span>
                        </div>
                        <div id="optionDIV" class="test_content_nr"></div>
                        <div class="col-lg-9 col-lg-offset-3">
                                <a id="sub" href="#">提交</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>    
    <jsp:include page="/website/INCLUDE/footer.jsp"></jsp:include>
        <form action="${ctx}/website/yjwd/investigate/findInvestigateOptionByPage.action" method="post" id="dataForm">
        <input type="hidden" name="rows" id="pageSize"> 
        <input type="hidden" name="page" id="pageNumber" value="1"> 
        <input type="hidden" name="totalPage" id="totalPage">
    </form>
        <script type="text/javascript" src="${ctx}/website/js/common.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $.ajax({
             type : "post",
             dataType : "json",
             url : "${ctx}/website/yjwd/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 += '<div name="divOptionTitle" class="test_content_nr_tt" id="div_0_'+i+'">'+ option.subject +'</div>';    
                    opHTML += '<div 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 += '</div>';
                    opHTML += '</li>';
                }
                opHTML += '</ul>';
                $('#optionDIV').html(opHTML);
             }
        })
    });
</script>
<script type="text/javascript">
$('#sub').click(function(){submitAnswer();});
function submitAnswer(){
    var userid = "${sessionScope.user.id}";
    var k = document.getElementById('sub').innerText;
    var investigateTitle = "${iyInvestigate.title}";
    var indvestigateID = "${iyInvestigate.id}";
    //获取同一个主题活动下的题目集合
    var subjectTitleCountObj = document.getElementsByName("divOptionTitle");
    //获取每一道题目以及相应的选项
    for (var k=0;k < subjectTitleCountObj.length;k++){
        //存储题目
        var subject = $("#div_0_"+ k).text();
        //存储选中的项
        var selectItem  = "";  
        var radios = document.getElementsByName("answer"+k);
        for (r = 0; r < radios.length;r++) {
            if (radios[r].checked) {
                selectItem = radios[r].nextSibling.data;
                var entries = [];
                entries[entries.length]={"investigateTitle": ${iyInvestigate.title},"investigateID":${iyInvestigate.id},"subjectOp":subject,"selectItemOp":selectItem,"userid":${sessionScope.user.id}};
                var newEntries = JSON.stringify(entries);
                var = $.post(                           
                    url:"${ctx}/website/yjwd/investigateResult/submitAnswer.action",
                    data:{"entries":entries}
                );
            }
        }
        $.ajax({
            type : "post",
            dataType : "json",
            url : "${ctx}/website/yjwd/investigate/submitAnswer.action",
            data : {"investigateTitle": ${iyInvestigate.title},"investigateID":${iyInvestigate.id},"subjectOp":subject,"selectItemOp":selectItem,"userid":${sessionScope.user.id}},
            success : function(rec){}
          }); 
    }
}
</script>
</body>
</html>