【问题标题】:Fetch data from db using ajax jquery使用ajax jquery从数据库中获取数据
【发布时间】:2014-11-22 15:30:39
【问题描述】:

我在我的 jquery 脚本中使用 ajax 从 db 获取值时遇到了一些问题。

index.php:

<?php include 'db/db_connection.php';?>
<?php include 'db/db_getvalues.php';?>

<div class="arrow">
  <img src="img/arrow_left.png" />
</div>

<div class="text-box"></div>

script.js

$(document).ready(function () {
  $(".arrow").click(function () {
    $.ajax({
      type: "GET",
      url: "../db/db_getvalues.php", // This is the correct path, but do jquery recognize "../db/" etc?
      dataType: "text",
      success: function (response) { // Here is where i'm lost, what do i need to write to update my innerHTML with the returned value from the db_getvalues.php-file?
        $(".text-box").html(response);
      }
    });
  });
});

db_getvalues.php // 这个文件有效,我直接从 html 文件中选择了数据

<?php
  function getdbvalues() {
    $query = 'SELECT * FROM mydb WHERE Id = 1';
    $fetch = mysql_query($query) or die ('Could not find tablerow');
    $row = mysql_fetch_assoc($fetch);

    $textString = $row['Text'];

    return $textString;
  }
?>

【问题讨论】:

  • 你目前得到什么输出?

标签: php jquery html mysql ajax


【解决方案1】:

是的,AJAX 可以识别这样的 URL。您的ajax 似乎还可以,但有一点建议可以更改db_getvalues.php。您应该回显该值而不是返回。我建议你调用getdbvalues() 函数并像下面这样回显它。

在 db_getvalues.php 中

function getdbvalues() {
    $query = 'SELECT * FROM mydb WHERE Id = 1';
    $fetch = mysql_query($query) or die ('Could not find tablerow');
    $row = mysql_fetch_assoc($fetch);
    $textString = $row['Text'];
    return $textString;
}

echo getdbvalues(); //Added

【讨论】:

    【解决方案2】:

    你必须确保 1.你的点击功能工作 2.你的ajax请求成功 3. php 正在生成一些要被 ajax 成功函数接收的 html 4. 你的 php 代码给你(回显)所需的 html

    检查我在代码中添加了 cmets(1,2,3,4) 的行

    $(document).ready(function () {
      $(".arrow").click(function () {
      alert("I am called"); //1
        $.ajax({
          type: "GET",
          url: "../db/db_getvalues.php", 
          dataType: "text",
          success: function (response) { 
          alert(response+" __ url is fine");//2
            $(".text-box").html(response);
          }
        });
      });
    });
    
    
    
    <?php
      echo "php is called"; //3
      function getdbvalues() {
        $query = 'SELECT * FROM mydb WHERE Id = 1';
        $fetch = mysql_query($query) or die ('Could not find tablerow');
        $row = mysql_fetch_assoc($fetch);
    
        $textString = $row['Text'];
    
        return $textString;
      }
    echo getdbvalues(); //4
    ?>
    

    【讨论】:

      猜你喜欢
      • 2019-11-05
      • 2014-05-03
      • 2012-12-14
      • 2017-03-04
      • 2021-04-01
      • 2019-11-26
      • 2023-03-27
      • 2021-02-11
      • 2014-10-17
      相关资源
      最近更新 更多