как сделать переменную для отображения этих данных на AJAX - PullRequest
0 голосов
/ 02 декабря 2018

У меня есть AJAX-код

 <script type="text/javascript">

    $(".monitor").click(function(){

        $("#list-format").html("");
        let nama_puskesmas = $(this).data('nama');
        let id_puskesmas = $(this).data('id');
        let nomor = $(this).data('nomor');
        let base_url = '<?php echo base_url();?>'


        $.ajax({
            url     : 'get_data',
            method  : 'post',
            dataType: 'json',
            data    : {id_puskesmas:id_puskesmas},
            success : function(response){

                $.each(response, function(i, obj){
                    $("#list-format").append("<li>"+obj.format+"</li>");
                });

                $("#title-modal").html(nama_puskesmas);
                $("#exampleModalCenter").modal('show');
                $("#button-submit").html(`<a href="${base_url}dinas/view_monitor/${id_puskesmas}" id="submit_modal" class="btn btn-primary">Lihat data</a>`)
                $("#button-submit2").html(`<a href="https://wa.me/${nomor}?text=Laporan%20Yang%20Masih%20Belum%20Lengkap%20Adalah%20Sebagai%20Berikut%20Ini" id="submit_modal" class="btn btn-primary">Kirim Pesan</a>`)


            }



        })      

    })
</script>

, при запуске эта программа будет выглядеть следующим образом

Data yang belum diupload
1.Form Lap PTM
2.Form Lap Posbindu
3.Form Lap IVA
4.Form Lap Jiwa
5.Form Lap Indera dan Gimul
6.Form Lap Diare
7.Form Lap LROA
8.Form Lap Thypoid
9.Form Lap Laporan Hiv Aids dan IMS
10.Form Laporan Hepatitis

, и я передам эти данные моей другой функции

Как я могу сделать переменную из этого кода:

 $.each(response, function(i, obj){
                    $("#list-format").append("<li>"+obj.format+"</li>");
                });

Чтобы повторить это:

$("#button-submit2").html(`<a href="https://wa.me/${nomor}?text=Laporan%20Yang%20Masih%20Belum%20Lengkap%20Adalah%20Sebagai%20Berikut%20Ini" id="submit_modal" class="btn btn-primary">Kirim Pesan</a>`)

или у кого-нибудь есть идея сделать это может повторить это # ​​button-submit2?спасибо большое :) извините за плохой английский

1 Ответ

0 голосов
/ 02 декабря 2018
<script type="text/javascript">
// this var contains a new element, which is not yet appended to the DOM
var $receivedItems = $('<div></div>');
$(".monitor").click(function(){

    $("#list-format").html("");
    let nama_puskesmas = $(this).data('nama');
    let id_puskesmas = $(this).data('id');
    let nomor = $(this).data('nomor');
    let base_url = '<?php echo base_url();?>'


    $.ajax({
        url     : 'get_data',
        method  : 'post',
        dataType: 'json',
        data    : {id_puskesmas:id_puskesmas},
        success : function(response){
            $.each(response, function(i, obj){
                // instead of echoing it directly by appending it to the DOM, store your list items in the hidden or not-appended element in your variable
                $receivedItems.append("<li>"+obj.format+"</li>");
                $("#list-format").append("<li>"+obj.format+"</li>");
            });

            // ..... your other stuff

            var buttonHtml = `<a href="https://wa.me/${nomor}?text=Laporan%20Yang%20Masih%20Belum%20Lengkap%20Adalah%20Sebagai%20Berikut%20Ini" id="submit_modal" class="btn btn-primary">Kirim Pesan</a>`;
            var $button2 = $(buttonHtml);

            $button2.on('click', function(e) {
                // be aware to use href only as a fallback if js does not work. otherwise your url will change and js won’t be executed
                e.preventDefault();
                // on click, you can append the list items stored in $receivedItems
                $("#list-format").append($receivedItems.children());
            });
            // be aware of nesting a and button tags, you shouldn’t
            $("#button-submit2").append($button2);

        }

    })      

})
</script>

Я положил некоторые комментарии в коде.При таком подходе вы можете хранить все полученные элементы в объекте jQuery, который еще не добавлен в узел DOM.Это будет происходить при активации события нажатия, которое добавляется к кнопке submit2.

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