【问题标题】:Jquery/Ajax to get database using phpJquery/Ajax 使用 php 获取数据库
【发布时间】:2021-04-01 19:25:38
【问题描述】:

我的 HTML 页面太大,无法在此处发布,但我将发布我用来尝试访问 PHP 文件变量的 ajax/jquery。

threadPage.html

<script type="text/javascript">
            
        $.ajax({
        url : '/ThreadCreation.php',
        type : 'POST',
        data: {'titles': titles}
        crossDomain: true,
        dataType : 'jsonp',
        success : function (data) {
           console.log(data) /
        },
        error : function () {
           alert("error");
        }
    })  

</script>

<!-- bunch of html -->

所以基本上我试图从 ThreadCreation.php 以 JSON 形式获取变量。它应该在一个数组中,以便我可以在 HTML 文件中循环遍历它。

ThreadCreation.php

<?php

    $username = 'root';
    $password = '';
    $db = 'main_database';

    $conn = mysqli_connect('localhost', $username , $password,$db);
    
    if (!$conn){
        die("unable to connect");
    }

    
   $sql = mysqli_query($conn, "SELECT title FROM thread");

   while($row = mysqli_fetch_array($sql)) {
   $titles[] = $row['title'];

   echo json_encode($titles);
?>

不过,我要重复一遍,这个 HTML 文件只是通过 PHP 从数据库中获取信息。所以这里没有表单提交。

我不断收到“未定义标题”的消息。这是有道理的,因为 HTML 中没有定义标题,但是我不确定如何构造我的 ajax 请求来收集数据,因为我见过人们使用这种格式。

【问题讨论】:

  • 你应该试试:var titles = &lt;?php echo json_encode($titles);?&gt;
  • @HoangHiey 即使它们在不同的文件中?
  • @kongar echo 前右括号。
  • 你尝试使用dataType : 'json'而不是dataType : 'jsonp'
  • @RobinSingh 它给了我语法错误。这是正确的var titles = &lt;?php (echo json_encode($titles));?&gt;

标签: javascript php html jquery ajax


【解决方案1】:

首先提到空数组只是为了防止在没有数据的情况下出错 在数据库中然后空数组将继续。

$sql = mysqli_query($conn, "SELECT title FROM thread");

$titles = array();
while ($row = mysqli_fetch_array($sql)) {
    array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2017-10-24
    • 1970-01-01
    • 2014-10-17
    相关资源
    最近更新 更多