簡體   English   中英

jQuery AJAX加載頁面內容

[英]jQuery AJAX loading page content

我正在嘗試重建我的網站,以便它使用AJAX在div中加載數據內容。 這是處理加載的函數:

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);
    })
}

問題在於,正在加載的內容通常(通常)包含更多的JS(庫以及帶有我的代碼的腳本標簽),通常無法正確執行。 此類響應的示例:

<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>

是否有任何適當的方式來加載此類內容並像正常頁面加載一樣執行js?

這是將ajax響應添加到容器后執行javascript的正確方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM