使用javascript / jquery / php构建动态网站并将html存储在mysql中

时间:2014-12-12 04:26:34

标签: javascript php html mysql dynamic

我是动态网站编码的新手,我的项目最终会扩展到相当大的

我无法从我的外部网站html文件或从我创建的外部PHP文件中获取我的javascript来从mysql表中提取内容。我也不太清楚如何将我的静态实现转换为动态实现,我在下面提供了静态版本和部分工作/不完整动态版本的详细信息。

点格式流程:

  • onclick javascript与php的对话
  • php与访问请求内容的mysql进行对话
  • mysql发送回php
  • php发送到javascript
  • javascript将内容附加,预先添加或加载(取决于我们希望它做什么)内容到网页上的特定DIV。

我有一个示例,它对静态html文件有些作用:

HTML页面上的HTML:

<a href="#" id="item1">item1</a>

将内容加载到的DIV:

<div id="content"></div>

HTML页面上的javascript:

<script>
        $('#item1').click(function() {

            $.get("item1.html",function (test) { $("#content").prepend(test);});
        });
</script>

上面的示例适用于在每次单击我们想要的链接时静态地预先添加代码而不清除“内容”DIV。但是,在尝试将此静态设置转换为动态设置时,我们无法执行此操作。

我还尝试了以下javascript更改,看看我们是否可以从外部源加载html,但它无法执行此操作(不确定为什么我的javascript不会加载外部页面? ):

<script>
            $('#item1').click(function() {

                $.get("http://localhost/item1.html",function (test) { $("#content").prepend(test);});
            });
    </script>

我认为对于动态外观结构的最终解决方案将是:

注意不起作用,只是概念

HTML会显示:

<a href="#" id="I8">item8</a>

javascript概念:

  • 通过PageContent.php onclick锚点链接传递ID到PageContent.php?id = I8
  • 等待PHP PageContent.php处理请求
  • php以HTML和javascript的形式将内容传回javascript,然后将内容预先添加/附加/加载到#content DIV。

PHP PageContent.php INCOMPLETE

<?php
$conn = mysqli_connect('localhost', 'user', 'pass', 'DB')
    or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

$sql = "SELECT * FROM `content` where ID='<? ID VARIABLE that was passed from javascript HERE ?>';";
$result = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result);
?>

我从来没有构建过你可以传递信息的php页面,并以这种方式获得结果,你有'?ID ='。你如何实现 PageContent.php的直通?ID = 8

1 个答案:

答案 0 :(得分:1)

让我们说你有index.php你的内容。 。然后在getContent.php上你有mysql查询来获取你的mysql表上的数据

$(function(){
    $('#item1').click(function(){
     var id = 5; //id of your mysql table row
     $.get("getContent.php?id=" + id,function(response){
       $('#content').html(response); //append the data return from content.php
         });
       });
 });

然后在你的getContent.php

$id = $_GET['id'];
//then here is your mysql query getting data by it's ID and store it in a variable
// sample is $mysqlContentData

  echo $mysqlContentData; // and also try using return $mysqlContentData;

它会将您的数据从getContent.php返回到index.php上的$ .get函数