简体   繁体   中英

jQuery AJAX loading page content

I'm trying to rebuild my site, so that it uses AJAX to load data content inside a div. This is the function, that handles the loading:

navigate = function(url, title, callback){
    //show message to user
    toastr.info('<i class="fa fa-spin fa-circle-o-notch"></i> Page is being loaded, please wait.');

    //default variables set
    title = title || url.substr(url.lastIndexOf('/') + 1).replace(/_/g, ' ').capitalize();
    callback = callback || function(){};

    //load content to wrapper
    $("#content-wrapper").load(url + "?" + $.param({page_load: true}), function(res, status, jqXHR){
        toastr.clear(); //hides message
        if(status === "error")
        {
            toastr.error('Page couldn\'t be loaded. Please try again later or contact your system administrator', jqXHR.status + ": " + jqXHR.statusText);
        }
        else if(status === "success")
        {
            History.pushState({page: url}, title + " | PCexpres manager", url);
        }

        //remove modals from inside the content and move them to the end of body - prevents problems with backdrop
        $('body > .modal').remove();
        $('.modal').each(function(){
                $(this).clone(true, true).appendTo("body");
                $(this).remove();
        })

        //execute custom callback
        callback(res, status, jqXHR);
    })
}

The problem is, that the content, which is being loaded, often (usually) contains more JS (libraries as well as script tags with my code), which is usually not executed correctly. Example of such response:

<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/datatables.js?1434971835"></script>
<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js?1434972105"></script>
<link type="text/css" rel="stylesheet" href="http://pce.local/assets/css/plugins/datatables/datatables.css?1434971143" />
<script>
    $(function() {
        $('.table').dataTable({
            dom: 'Rlfrtip',
            stateSave: true,
            processing: true,
            serverSide: true,
            searchHighlight: true,
            ajax: "http://pce.local/technician/customers/index_processing.json",
            columns: [{
                data: "checkbox",
                name: "return 'id'"
            }, {
                data: "id",
                name: "return 'id'"
            }, {
                data: "last_name",
                name: "return 'last_name'"
            }, {
                data: "first_name",
                name: "return 'first_name'"
            }, {
                data: null,
                render: function(customer) {
                    return customer.address + (((customer.address_city !== "" || customer.address_zip !== "") && (customer.address !== "")) ? ", " : "") + customer.address_zip + " " + customer.address_city;
                },
                name: "return 'first_name'"
            }, {
                data: "email",
                name: "return 'email'"
            }, {
                data: "phone1",
                name: "return 'phone1'"
            }, {
                data: "actions",
                name: "return 'id'"
            }],
            stateSave: true,
            order: [
                [1, "desc"]
            ],
            aoColumnDefs: [{
                'bSortable': false,
                'aTargets': [0, -1]
            }],
            iDisplayLength: 50,
            language: {
                lengthMenu: "Display <select><option value='25'>25</option><option value='50'>50</option><option value='100'>100</option><option value='200'>200</option><option value='500'>500</option></select> records per page"
            }
        });

        $(".check_all").change(function() {
            $(".content_wrapper :checkbox").prop("checked", $(this).is(":checked"))
        })
        $("#delete_checked").click(function() {
            var ids = '';
            $(".delete_one:checked").each(function() {
                    ids += $(this).attr('data-id') + ',';
                })
                //remove last comma
            ids.slice(0, -1)

            if (confirm('Are you sure?'))
                window.location.href = "http://pce.local/technician/customers/delete/" + ids
        })
        $(document).on('click', '.delete_customer', function(e) {
            e.preventDefault();
            $me = $(this);
            bootbox.dialog({
                title: "Delete customer?",
                message: "Are you sure, you want to delete this customer?",
                buttons: {
                    nope: {
                        label: "No",
                        className: "btn-default",
                        callback: function() {
                            toastr.success('Deletion cancelled');
                        }
                    },
                    yep: {
                        label: "Yes",
                        className: "btn-warning",
                        callback: function() {
                            window.location.href = $me.attr('href');
                        }
                    },
                    yeah: {
                        label: "Yes, delete data as well",
                        className: "btn-danger",
                        callback: function() {
                            window.location.href = $me.attr('href') + '/1';
                        }
                    }
                }
            });
        })
    });
</script>
<div class="content_wrapper">
    <a class="btn btn-primary btn-md" href="http://pce.local/technician/customers/add">+</a>
    <table class="table table-condensed table-striped table-hover pce-list_table">
        <thead>
            <th>
                <input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
            </th>
            <th>ID</th>
            <th>Last name</th>
            <th>First name</th>
            <th>Address</th>
            <th>E-mail</th>
            <th>Phone</th>
            <th>Actions</th>
        </thead>
        <tfoot>
            <th>
                <input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
            </th>
            <th>ID</th>
            <th>Last name</th>
            <th>First name</th>
            <th>Address</th>
            <th>E-mail</th>
            <th>Phone</th>
            <th>Actions</th>
        </tfoot>
        <tbody>
        </tbody>
    </table>
    <button id="delete_checked" class="btn btn-primary btn-md" data-nosubmit="data-nosubmit" name="delete_checked">Delete checked</button>
</div>

Is there any proper way to load such content and execute the js as if it was a normal page load?

Here is the correct way to execute javascript after ajax response is added to the container

var arr = document.getElementById('myDiv').getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
{
   eval(arr[n].innerHTML)//run script inside div
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM