0

Пытаюсь послать со страницы запрос в БД и получить ответ в html таблицу с помощью AJAX xmlHttpRequest. На странице есть поисковая форма, ввожу слово форма отправляется на сервкр контроллер обрабатывает и Spring Data JPA делает Custom запрос в базу (findAllByName(Sting name)) вот это String name это слово из формы, затем БД возвращает результат и должна без перезагрузки страницы отобразить в таблице на этой же html странице, но страницв перезагружется и данные отображаются просто как JSON обьект. подскажите где ошибка в функции.

<body>

<div id="home">

    <div id="srch">
        <h1>Search over <span>17,000 aircraft</span> for sale!</h1>
        <!--/*@thymesVar id="myInput" type=""*/-->
        <form id="hm_search" class="hm_search" th:object="${myInput}" name="hm_search" th:action="@{/api/aircrafts}" method="post" accept-charset="utf-8">
            <div id="srchbdr">
                <input type="text" placeholder="Search by Make, Model or Country" id="GpsSearchQueryBox" th:name="aircraftName" th:id="aircraftName"  class="input_text">
                <button id="goButton" class="bt_hmsrch" type="submit"><i class="fas fa-search fa-fw"></i>Search</button>
            </div>
        </form>

    </div>
</div>

<div class="table-users">
<div class="header">Aircraft</div>
<table id="usersList" style="width: 100%">

</table>
</div>

<script>
    function loadAircraft() {
        var form = $('#hm_search');
        form.onsubmit = function (event) {
            event.preventDefault();
            var formData = new FormData(form);
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var aircrafts = JSON.parse(this.responseText);
                    var html = '<tr>\n' +
                        '<th> Picture</th>\n' +
                        '        <th>Id</th>\n' +
                        '        <th>Manufacturer/model</th>\n' +
                        '        <th>Year</th>\n' +
                        '        <th>Location</th>\n' +
                        '        <th>S/N</th>\n' +
                        '        <th>TTAF</th>\n' +
                        '<th>Reg Nr.</th>\n' +
                        '        <th>Owner</th>\n' +
                        '    </tr>';
                    for (var i = 0; i < aircrafts.length; i++) {
                        var planes = aircrafts[i];
                        console.log(planes);
                        html = html + '<tr><td><img src="/img/' + planes.img + '" alt="pic" /></td>' +
                            '<td>' + planes.aircraftId + '</td>\n' +
                            '        <td>' + planes.name + '</td>\n' +
                            '        <td>' + planes.manufacture + '</td>\n' +
                            '        <td>' + planes.location + '</td>' +
                            '        <td>' + planes.sn + '</td>' +
                            '    <td>' + planes.ttaf + '</td>' +
                            '<td>' + planes.reg + '</td>' +
                            '        <td>' + planes.owner.name + '</td></tr>';

                    }
                    document.getElementById("usersList").innerHTML = html;
                }
            };
            xhttp.open("POST", "http://localhost:8080/api/aircrafts", true);

            xhttp.send(formData);
        }
    }

    loadAircraft();

</script>
@RestController
@RequestMapping("/api")
public class AircraftAPI {

    @Autowired
    private AircraftService airService;

    @PostMapping("/aircrafts")
    public List<Aircraft> showAll (@ModelAttribute("myInput") Input input) {
            if(input.getAircraftName()!=null){
                
                return airService.findAllByName(input.getAircraftName());
            }
        
        return airService.getAll();
    }

}
3
  • На бэке напишите API, что бы ваш фронт просто делал на него запросы и получал ответы в виде JSON
    – ccvhd
    13 июн 2020 в 13:30
  • когда я вижу var = 'text' + var + 'text' мне хочется убивать, тем более когда text = html
    – Vadim
    13 июн 2020 в 13:39
  • Он итак отдает JSON.. 13 июн 2020 в 13:43

1 ответ 1

0

Вопрос решен

<script>
    function loadAircraft() {
        var form = $('#hm_search');
        form.onsubmit = function (event) {
            event.preventDefault();}
            var formData = new FormData(document.getElementById("hm_search"));
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var aircrafts = JSON.parse(this.responseText);
                    var html = '<tr>\n' +
                        '<th> Picture</th>\n' +
                        '        <th>Id</th>\n' +
                        '        <th>Manufacturer/model</th>\n' +
                        '        <th>Year</th>\n' +
                        '        <th>Location</th>\n' +
                        '        <th>S/N</th>\n' +
                        '        <th>TTAF</th>\n' +
                        '<th>Reg Nr.</th>\n' +
                        '        <th>Owner</th>\n' +
                        '    </tr>';
                    for (var i = 0; i < aircrafts.length; i++) {
                        var planes = aircrafts[i];
                        console.log(planes);
                        html = html + '<tr><td><img src="/img/' + planes.img + '" alt="pic" /></td>' +
                            '<td>' + planes.aircraftId + '</td>\n' +
                            '        <td>' + planes.name + '</td>\n' +
                            '        <td>' + planes.manufacture + '</td>\n' +
                            '        <td>' + planes.location + '</td>' +
                            '        <td>' + planes.sn + '</td>' +
                            '    <td>' + planes.ttaf + '</td>' +
                            '<td>' + planes.reg + '</td>' +
                            '        <td>' + planes.owner.name + '</td></tr>';

                    }
                    document.getElementById("usersList").innerHTML = html;
                }
            };
            xhttp.open("POST", "http://localhost:8080/api/aircrafts", true);

            xhttp.send(formData);

    }
    $(function() {
        $("#goButton").click(function(e) {
            e.preventDefault(); 

            loadAircraft();
        })
    });
                



</script>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.