Javascript 使用 AJAX 将 HTML 插入页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3032767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:00:15  来源:igfitidea点击:

Insert HTML into a page with AJAX

javascripthtmlxmlajax

提问by siannone

I am currently developing a website and i need that the pages loads dynamically based on what actions the user does.

我目前正在开发一个网站,我需要根据用户执行的操作动态加载页面。

Example: If the user clicks on the button 'Settings' an ajax function will load from an external page the code and will put into the div with tag 'settings'.

示例:如果用户单击“设置”按钮,ajax 函数将从外部页面加载代码并将其放入带有“设置”标签的 div。

This is the code i use to make the Ajax request:

这是我用来发出 Ajax 请求的代码:

    function get_page_content(page, target_id)
    {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById(target_id).innerHTML = xmlhttp.responseText;
                // After getting the response we have to re-apply ui effects or they
                // won't be available on new elements coming from request.
                $('button').sb_animateButton();
                $('input').sb_animateInput();
            }
        }
        xmlhttp.open('GET', 'engine/ajax/get_page_content.php?page=' + page, true);
        xmlhttp.send();
    }

And this is where the ajax results will be put by first snippet:

这是第一个片段将放置 ajax 结果的地方:

<div id="settings_appearance">                
</div>

The code is called from a function here:

代码是从这里的函数调用的:

<div class="left_menu_item" id="left_menu_settings_appearance" onclick="show_settings_appearance()">
    Appearance
</div>

And this is the html that the ajax function will put into the settings_appearancediv:

这是 ajax 函数将放入settings_appearancediv的 html :

    <script type="text/javascript">
        $(function()
        {
            $('#upload_hidden_frame').hide();
            show_mybrain();

            document.getElementById('avatar_upload_form').onsubmit = function()
            {
                document.getElementById('avatar_upload_form').target = 'upload_hidden_frame';
                upload_avatar();
            }
        });
    </script>
    <div class="title">Appearance</div>
    <iframe id="upload_hidden_frame" name="upload_hidden_frame" src="" class="error_message"></iframe>
    <table class="sub_container" id="avatar_upload_form" method="post" enctype="multipart/form-data" action="engine/ajax/upload_avatar.php">
        <tr>
            <td><label for="file">Avatar</label></td>
            <td><input type="file" name="file" id="file" class="file_upload" /></td>
            <td><button type="submit" name="button_upload">Upload</button></td>
        </tr>
        <tr>
            <td><div class="hint">The image must be in PNG, JPEG or GIF format.</div></td>
        </tr>
    </table>

I would like to know if there's a way to execute also the javascript code that's returned by the ajax function (upload button in the returncode doesn't work because of this) and if it's possible to apply some customized ui effects i build that are loaded with the main page.

我想知道是否还有一种方法可以执行 ajax 函数返回的 javascript 代码(返回代码中的上传按钮因此不起作用),以及是否可以应用我构建的一些自定义 ui 效果已加载与主页。

Thanks for helping.

谢谢你的帮助。

P.S. This is the script that applies the UI effects:

PS 这是应用 UI 效果的脚本:

<script type="text/javascript">
// UI effects
$(document).ready(function()
{
  $('button').sb_animateButton();
  $('input').sb_animateInput();
  $('.top_menu_item').sb_animateMenuItem();
  $('.top_menu_item_right').sb_animateMenuItem();
  $('.left_menu_item').sb_animateMenuItem();
});
</script>

P.P.S. ui effects are not applied to html elements (such as input and buttons) returned by the Ajax function. I used a little workaround by applying again ui-effects after ajax function returns the response. Probably there's another way of doing it... the same that will help me solve this problem.

PPS ui 效果不适用于 Ajax 函数返回的 html 元素(例如输入和按钮)。我通过在 ajax 函数返回响应后再次应用 ui-effects 来使用一些解决方法。可能还有另一种方法……同样可以帮助我解决这个问题。

采纳答案by ckramer

If you use the jQuery ajax function(or the simplified jQuery get function), and set the datatype to html, then jQuery will evaluate the contents of any script tags included in the results.

如果您使用 jQuery ajax 函数(或简化的 jQuery get 函数),并将数据类型设置为 html,那么 jQuery 将评估结果中包含的任何脚本标记的内容。

Your $.get call would look something like:

你的 $.get 调用看起来像:

$.get('engine/ajax/get_page_content.php?page=' + page,null,function(result) {
    $("#"+target_id).html(result); // Or whatever you need to insert the result
},'html');

回答by Aaron Harun

I also suggest you don't, but after loading the content in the div, pass the element ID to this function. This will even handle document.write

我也建议你不要,但是在 div 中加载内容后,将元素 ID 传递给这个函数。这甚至可以处理 document.write

function do_JS(e){
        var Reg = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
        var match    = new RegExp(Reg, 'img');
        var scripts  = e.innerHTML.match(match);
        var doc = document.write;
        document.write = function(p){ e.innerHTML = e.innerHTML.replace(scripts[s],p)};
        if(scripts) {
            for(var s = 0; s < scripts.length; s++) {
                var js = '';
                var match = new RegExp(Reg, 'im');
                js = scripts[s].match(match)[1];
                js = js.replace('<!--','');
                js = js.replace('-->','');
                eval('try{'+js+'}catch(e){}');
            }
        }
        document.write = doc;
    }

A better solution will be to add a function that you can call at the end of the update to show the effects.

更好的解决方案是添加一个函数,您可以在更新结束时调用该函数以显示效果。

回答by the_drow

I recommend you not to, it might lead to a security breach.
If you already use jquery, use it's ajax functionallity instead of the raw one.
When the ajax request completes execute the animation code (just leave it on the page that does the ajax call).

我建议您不要这样做,这可能会导致安全漏洞。
如果您已经使用 jquery,请使用它的 ajax 功能而不是原始功能。
当 ajax 请求完成时执行动画代码(只需将其留在执行 ajax 调用的页面上)。

回答by Garis M Suero

In your content HTML (the one you get from the call) make a common javascript function for every content page, that will be called every time the content is loaded on the master page...

在您的内容 HTML(您从调用中获得的那个)中,为每个内容页面创建一个通用的 javascript 函数,每次在母版页上加载内容时都会调用该函数...

the function name will be something like: loadContentJavascript() {}

函数名称类似于:loadContentJavascript() {}

and this function is in charge of loading all the functionalities that it will be load on a onload event.

这个函数负责加载将在 onload 事件上加载的所有功能。