AJAX-вызов работает на странице JSP, но не при ее импорте - PullRequest
0 голосов
/ 21 октября 2019

Итак, у меня есть вызов ajax:

$.ajax({
        url: '${pageContext.request.contextPath}/filial/select.json',
        method: 'GET',
        success: function (json) {
            var itens=[];

            for (var i = 0; i < json.length; i++) {
                itens.push('<input id= "idFilial'+json[i][0]+'" type = checkbox class=checkbox1 name = filiaisId value="'+json[i][0]+'">' +json[i][1]+"-"+ json[i][2]  + '</input></br>');
            }
            $('#idFilial').html($("<tbody/>", {html:itens}));
            $('.filiaisId').each(function(){
                $( "#idFilial"+ $(this).attr('value')).prop( "checked", true);
            });
        },
        error: function () {
            console.log("Path \"/filial/select.json\" not found!");
        }

    });

И на этой странице JSP он прекрасно работает:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="icon" href="${pageContext.request.contextPath}/resources/landing_page/img/dunning_16.ico">
    <title>DUNNING - Relatórios Personalizados</title>

    <c:import url="template/include_css.jsp"/>
</head>
<body>
<div id="wrapper">
    <c:import url="template/menu.jsp" />
    <div id="page-wrapper" class="gray-bg">
        <c:import url="template/header.jsp" />
        <!--Some code here-->
        <c:import url="template/footer.jsp"/>
    </div>
</div>
<c:import url="template/include_js.jsp"/>
<c:import url="template/include_js_datatables.jsp" />
<c:import url="template/include_js_highcharts.jsp"/>
<script src="${pageContext.request.contextPath}/resources/js/plugins/chosen/chosen.jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#menu-relatorios').addClass("active");
        $('#menu-relatorios-in').addClass("collapse in");
        $('#menu-relatorio-personalizado').addClass("active");
        $('#botao-download').click(function() {
            window.location='${pageContext.request.contextPath}/relatorio_personalizado/download';
        });
        $.ajax({
            url: '${pageContext.request.contextPath}/filial/select.json',
            method: 'GET',
            success: function (json) {
                var itens=[];

                for (var i = 0; i < json.length; i++) {
                    itens.push('<input id= "idFilial'+json[i][0]+'" type = checkbox class=checkbox1 name = filiaisId value="'+json[i][0]+'">' +json[i][1]+"-"+ json[i][2]  + '</input></br>');
                }
                $('#idFilial').html($("<tbody/>", {html:itens}));
                $('.filiaisId').each(function(){
                    $( "#idFilial"+ $(this).attr('value')).prop( "checked", true);
                });
            },
            error: function () {
                console.log("Caminho \"/filial/select.json\" não encontrado!");
            }
        });
    });
</script>
</body>
</html>

Теперь, если вы заметили, есть импорт для другой страницы JSP под названием "header.jsp" <c:import url="template/header.jsp" />, верно? И вот где находится идентификатор idFilial! Вот это ниже:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

<!-- HEADER jsp fragment -->
<div class="row no-padding">

	<nav class="navbar navbar-static-top" role="navigation">
		
		<!-- Some Code here-->
						<div class="col-md-12" id="idFilial">
		<!--Some more code here-->
	</nav>
</div>
<script type="text/javascript">
	$(document).ready(function () {
		<!-- some more pointless code here-->
		$.ajax({
			url: '${pageContext.request.contextPath}/filial/select.json',
			method: 'GET',
			success: function (json) {
				var itens=[];

				for (var i = 0; i < json.length; i++) {
					itens.push('<input id= "idFilial'+json[i][0]+'" type = checkbox class=checkbox1 name = filiaisId value="'+json[i][0]+'">' +json[i][1]+"-"+ json[i][2]  + '</input></br>');
				}
				$('#idFilial').html($("<tbody/>", {html:itens}));
				$('.filiaisId').each(function(){
					$( "#idFilial"+ $(this).attr('value')).prop( "checked", true);
				});
			},
			error: function () {
				console.log("Caminho \"/filial/select.json\" não encontrado!");
			}

		});
	});
</script>

Вот и все! Я импортирую эту страницу заголовка в другие части моего кода. Но по какой-то причине, вызов ajax просто запускается на самих страницах, как на relatorio_personalizado.jsp, который я использовал в качестве примера, и не выполняет вызов на header.jsp сам! Я импортирую эту страницу заголовка с моим идентификатором в миллиард различных мест в коде, поэтому было бы идеально привязать вызов AJAX к этому импорту, вместо того, чтобы копировать и вставлять вызов ajax во все представления на моем веб-сайте. ! Кто-нибудь знает, что я делаю не так? Могу ли я использовать тег <script> при импорте?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...