【问题标题】:How to include php file into my html file? [closed]如何将 php 文件包含到我的 html 文件中? [关闭]
【发布时间】:2015-04-25 23:19:00
【问题描述】:

这是我的 index.php:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Voting Page</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

    //####### on page load, retrive votes for each content
    $.each( $('.voting_wrapper'), function(){

        //retrive unique id from this voting_wrapper element
        var unique_id = $(this).attr("id");

        //prepare post content
        post_data = {'unique_id':unique_id, 'vote':'fetch'};

        //send our data to "vote_process.php" using jQuery $.post()
        $.post('vote_process.php', post_data,  function(response) {

                //retrive votes from server, replace each vote count text
                $('#'+unique_id+' .up_votes').text(response.vote_up +' user has voted'); 
            },'json');
    });



    //####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
    $(".voting_wrapper .voting_btn").click(function (e) {

        //get class name (down_button / up_button) of clicked element
        var clicked_button = $(this).children().attr('class');

        //get unique ID from voted parent element
        var unique_id   = $(this).parent().attr("id"); 


        if(clicked_button==='up_button') //user liked the content
        {
            //prepare post content
            post_data = {'unique_id':unique_id, 'vote':'up'};

            //send our data to "vote_process.php" using jQuery $.post()
            $.post('vote_process.php', post_data, function(data) {

                //replace vote up count text with new values

                $('#'+unique_id+' .up_votes').text(data);
                //thank user for liking the content
dataModified = data+' users has voting including you';
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
            }).fail(function(err) { 

            //alert user about the HTTP server error
            alert(err.statusText); 
            });
        }

    });
    //end 

});

</script>
<style type="text/css">
<!--
.content_wrapper{width:500px;margin-right:auto;margin-left:auto;}
h3{color: #979797;border-bottom: 1px dotted #DDD;font-family: "Trebuchet MS";}

/*voting style */
.voting_wrapper {display:inline-block;margin-left: 20px;}
.voting_wrapper .up_button {background: url(images/index.png) no-repeat;float: left;width: 50px;cursor:pointer;}
.voting_wrapper .up_button:hover{background: url(images/index.png) no-repeat;}
.voting_btn{float:left;margin-right:5px;}
.voting_btn span{font-size: 11px;float: left;margin-left: 3px;}

-->
</style>
</head>

<body>
<div class="content_wrapper">
    <h3><img src="9780143332497.jpg" alt=""><br />

        <!-- voting markup -->
        <div class="voting_wrapper" id="1001">
            <div class="voting_btn">
                <div class="up_button">&nbsp;</div><span class="up_votes"></span>
            </div>
        </div>
        <!-- voting markup end -->
    </h3>
<span id="message-status"></span>
</div>
</body></html>

和 vote_process.php:

<?php
    ####### db config ##########
    $db_username = 'root';
    $db_password = '';
    $db_name = 'voter';
    $db_host = 'localhost';
    ####### db config end ##########

if($_POST)
{

    ### connect to mySql
    $sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');

    //get type of vote from client
    $user_vote_type = trim($_POST["vote"]);

    //get unique content ID and sanitize it (cos we never know).
    $unique_content_id = filter_var(trim($_POST["unique_id"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

    //Convert content ID to MD5 hash (optional)
    $unique_content_id = hash('md5', $unique_content_id);

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 


    switch ($user_vote_type)
    {           

        ##### User liked the content #########
        case 'up': 

            //check if user has already voted, determined by unique content cookie
            if (isset($_COOKIE["voted_".$unique_content_id]))
            {
                header('HTTP/1.1 500 User Already Voted'); //cookie found, user has already voted
                exit(); //exit script
            }

            //get vote_up value from db using unique_content_id
            $result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
            $get_total_rows = mysqli_fetch_assoc($result);

            if($get_total_rows)
            {
                //found record, update vote_up the value
                mysqli_query($sql_con,"UPDATE voting_count SET vote_up=vote_up+1 WHERE unique_content_id='$unique_content_id'");
            }else{
                //no record found, insert new record in db
                mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_up) value('$unique_content_id',1)");
            }

            setcookie("voted_".$unique_content_id, 1, time()+7200); // set cookie that expires in 2 hour "time()+7200".
            echo ($get_total_rows["vote_up"]+1); //display total liked votes
            break;  

        ##### respond votes for each content #########      
        case 'fetch':
            //get vote_up and vote_down value from db using unique_content_id
            $result = mysqli_query($sql_con,"SELECT vote_up,vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
            $row = mysqli_fetch_assoc($result);

            //making sure value is not empty.
            $vote_up    = ($row["vote_up"])?$row["vote_up"]:0; 

            //build array for php json
            $send_response = array('vote_up'=>$vote_up, 'vote_down'=>$vote_down);
        echo json_encode($send_response);
            break;

    }

}
?>

这是我现有的 html 工作 jsfiddle:http://jsfiddle.net/grkzcc5u/

我已经在php[index.php和vote_process.php]中创建了投票系统,所以

我需要将以上两个 php 文件添加到我的 index html 文件中。

对我来说这是新的想法,我对此一无所知。

谁能帮我解决这个问题?

【问题讨论】:

  • 您不能在 HTML 文件中包含 PHP 文件。你可以使用include 'vote_process.php',但它是PHP代码,所以它必须在PHP文件中
  • 重复? link 和 link 看看其中一个链接是否对您有帮助。
  • 我已经用html创建了很多网页,所以只有投票系统的目的我可以使用php..没有办法吗?
  • @lmarcelocc:我从这个stackoverflow.com/questions/11312316/…得到了答案,但我只是困惑如何跟随?

标签: javascript php jquery html


【解决方案1】:

您可以首先清理您的 HTML 文件,方法是将您的 CSS 存储在外部文件中,然后将其添加到页面顶部的标签和开始标签之间:

<link href="/path/to/stylesheet.css" type="">

然后将您的脚本存储在一个外部文件中,并将其链接到页面底部,就在标签上方,如下所示:

<script src="path/to/external/file"></script>

然后将您的 HTML 文件扩展名更改为 .php,以便 PHP 渲染引擎知道该文件确实是 PHP。

开始在您的代码中使用包含和要求。这样,您可以将所有代码拆分为可管理的模块。最好将所有函数存储在 functions.php 文件中,然后在索引中,在顶部开始 html 标记上方调用它,并带有:

<?php require ('functions.php'); ?>
<html>

您的所有包含应该看起来相似,但在它们自己的目录中并且看起来像:

<?php include ('includes/header_inc.php'); ?>

这就是我编写包含文件的方式。最后的 _inc 是可选的。你可以离开它像

header.php

我是新来的,如果您觉得难以理解,我深表歉意。 这是官方页面的链接,以便您更好地了解包括: http://php.net/manual/en/function.include.php

对于要求:http://php.net/manual/en/function.require.php

请记住以 .php 而不是 .html 结束您的 php 文件,否则您的代码将不会被 PHP 引擎解析。 在您对所包含链接中的内容感到满意后,请仔细阅读文档。

【讨论】:

  • 没有@nathan stephens:我只需要html扩展名..因为我在html文件中做了所有事情..如果你能解释这个链接stackoverflow.com/questions/11312316/…?
  • 礼貌不花钱。你给自己做了一个 .htaccess 文件吗?
  • 我无法理解@nathan stephens,上面的链接,我只需要html扩展
  • 网页浏览器在渲染站点根目录下的各种文件中的代码时,会检查每个文件中的文件扩展名,以了解文件是否需要通过 JavaScript 解析引擎、PHP 引擎、CSS 引擎等。PHP 引擎无法解析您的 PHP 代码,因为 PHP 引擎不知道您的 HTML 文件中有 PHP 代码。您需要将 .html 更改为 .php 以便 PHP 引擎获取文件。
【解决方案2】:

您不能在 javascript 中包含 PHP 文件,因为 PHP 仅对 PHP 解析器“可读”(这就是可以包含在服务器中的内容), 但是您可以使用 Ajax 例如。 http://www.ajax-tutor.com/post-data-server.html

function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End

    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('div1').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

    var userid = document.getElementById("userid").value;

    // 3. Specify your action, location and Send to the server - Start 
    xhr.open('POST', 'verify.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("userid=" + userid);
    // 3. Specify your action, location and Send to the server - End
}

【讨论】:

  • 请问,如何将您的答案转移到我现有的代码中?谢谢
  • xhr.open('POST', 'YOUR PHP FILE'); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(data); 其中“数据”是您要发送到表单的信息。 @rishi
  • 这些代码必须添加到我的 index.html 文件中,对吗? @mort
  • @rishi 是并绑定 onclick 发送按钮以防止默认并使用函数 PostData()。 `$('yourbutton').click(function(event){ event.preventDefault(); PostData(); }.
  • 我只是把@mort弄糊涂了,你必须帮助我..好吗?
【解决方案3】:

将其重命名为 index.php 并插入 php include

<?php include ("file_name"); ?>

如果你真的希望 html 在 php 模式下工作,你需要从服务器端启用它。

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 2013-12-04
    • 2016-11-04
    • 2017-09-30
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多