简体   繁体   English

jQuery AJAX加载页面内容

[英]jQuery AJAX loading page content

I'm trying to rebuild my site, so that it uses AJAX to load data content inside a div. 我正在尝试重建我的网站,以便它使用AJAX在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. 问题在于,正在加载的内容通常(通常)包含更多的JS(库以及带有我的代码的脚本标签),通常无法正确执行。 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? 是否有任何适当的方式来加载此类内容并像正常页面加载一样执行js?

Here is the correct way to execute javascript after ajax response is added to the container 这是将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