使用不带 iframe 的 JavaScript 将工作 PHP 文件(带脚本)拉入 div

Pull working PHP file (with scripts) into div using JavaScript without iframes

在系统限制下工作,我需要一种方法将本地 .php 或 .html 中的工作代码放入目标 div 中,而无需额外的库、jfiddle、iframe、等等(jquery 很好)

这是我失败的尝试。

文件的第一部分

<a href="#" id="fruit"> This is some page!</a>
<script>$("#fruit").click(function(){Expand01("fruit.php"); return false;});</script>

<a href="#" id="orange"> A pretty good page...</a>
<script>$("#orange").click(function(){Expand01("orange.php"); return false;});</script>

<a href="#" id="tomato"> I like this page</a>
<script>$("#tomato").click(function(){Expand01("tomato.php"); return false;});</script>

稍后在文件中(声明 Expand01 函数后)

<div id="thisdiv"></div>

尝试 1

<script> function Expand01(targetUrl){  
    document.getElementById('thisdiv').style.display = "block";
    document.getElementById('thisdiv').innerHTML = targetUrl;
    document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script> 

尝试 2

<script> function Expand01(targetUrl){
    var myTargetUrl = new XMLHttpRequest();
    document.getElementById('thisdiv').style.display = "block";
    myTargetUrl.open("GET", targetUrl, true);
    myTargetUrl.setRequestHeader("Content-Type","text/plain");
    myTargetUrl.send("");
    document.getElementById('thisdiv').innerHTML = myTargetUrl.responseText;
    document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script>

尝试 3

<script> function Expand01(targetUrl){
    document.getElementById('thisdiv').innerHTML = $.get(targetURL);
} </script>

尝试 4

<script> function Expand01(targetUrl){
    var myFile = getHTTPObject();
    myFile.onreadystatechange = function() {
        if(request.readyState == 4) {
            if(myFile.status == 200 || request.status == 304) {
                var targetDiv = document.getElementById('thisdiv');
                targetDiv.innerHTML = myFile.responseText;
            } else {
                alert("Failure");
            }
        }
    }
    myFile.open("GET", targetUrl, true);
    myFile.send(null);
} </script>

这是我为 ajax 应用程序执行此操作时使用的方法。它还允许使用 $_SESSION[] 变量以及任何位于 php 文件中的 Javascript 或 jQuery ,您正在拉入您的容器。

jQuery:

$.post('pageloader.php', {url: 'path/to/file.php'}, function(data){
    var o = $.parseJSON(data);
    if(o.status == 1){
        $('#yourContainer').html(o.markup);
    } else {
        alert(o.message);
    }
});

PHP: (pageloader.php)

$url = $_POST['url'];
$response = array();

ob_start();
include("markup/" . $url); // Replace or remove '"markup/" . ' depending on file locations  
$response['markup'] = ob_get_clean();

if($response['markup']){
    $response['status'] = 1;
} else {
    $response['status'] = 0;
    $response['message'] = 'There was an issue loading the page.';
}

echo json_encode($response);

希望对您有所帮助!