简体   繁体   中英

Return Seperate PHP Script Within HTML

I have a "print.php" script that basically fetches data from MySQL and creates a tiny pretty HTML table.

echo "
    <table cellpadding=\"2\" cellspacing=\"2\" border=\"0\" width=\"10%\">
        <tr bgcolor=\"#666666\">
            <td colspan=\"2\" align=\"center\"><b><font color=\"#FFFFFF\">" . $table[0] . "</font></td>
        </tr>
        <tr>
            <td>Name</td>
            <td>Score</td>
        </tr>";
echo "<tr";

    if ($i % 2 == 0)
        echo " bgcolor=\"#CCCCCC\"";

    echo ">
        <td>" . $col['player'] . "</td>
        <td>" . $col['score'] . "</td>
    </tr>";

I want this table to appear in my index.html, But its in a separate php script.

I want to keep the php script separate from the HTML because the script is not only a tad large, but it has my SQL information in it to which I don't want in the plain HTML.

Is there a way to fetch this echo in my php script from my html page?

Option 1: Use an iframe. Works even if JavaScript is turned off.

<iframe src="print.php"></iframe>

Option 2: Use AJAX (with jQuery).

Download jQuery here.

Include it in your index.html , preferably in your head tag.

<script type="text/javascript" src="path/to/jquery.js"></script>

Add this code where you want print.php to be included.

<div id="container"></div>

<script type="text/javascript">
    $(function(){
        $("#container").load("print.php");
    });
</script>

Option 3: Go the PHP route. May break other code since you need to rename the index file.

Rename your index.html to index.php and use this code:

<?php include("print.php"); ?>

You can make a AJAX call to the print.php from the your current page and fetch the data and show them.

$.ajax({
  url: "print.php"
}).done(function( html ) {
  $("#results").append(html); //results is the div id
});

You will have to get the basic jQuery knowledge for this.

Else you can use .load method which is also a AJAX method.

<div id="results"></div>

$("#results").load("print.php");

You can use AJAX Javascript to do that.

Documentation And Examples

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