dongliao8069 2019-01-16 17:35 采纳率: 0%
浏览 172
已采纳

如何使用ajax和jquery从我的数据库中检索记录?

I'm trying to retrieve records from my db using a button without the page refreshing. I'm not familiar with ajax and i've been having a hard time getting it to work. Here's what I have so far. any help would be appreciated, thank you

<h3>Avaiable assignments</h3><br>
<script>
 $(document).ready(function () {
$('#button1').click(function (e) {
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: "getItem.php",
        dataType: "html",
        success: function (msg) {
            if (msg.success) {
            $("#responsecontainer").html(msg);
        } else {
            alert("error");
        }
    }
    });
  });
});
<br>
 <input name="button1" type="submit" id="button1" 
value="Picked" />

my getItem.php

<?php
include("connect.php");
$q = intval($_GET['q']);


if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"items");
$sql="SELECT * FROM items WHERE LIMIT 1 OFFSET 1";
$result = mysqli_query($con,$sql);


while($row = mysqli_fetch_array($result))
{
echo $row['items'];
}

mysqli_close($con);
?>
  • 写回答

1条回答 默认 最新

  • duanca3415 2019-01-16 17:47
    关注

    Your best bet is to start in the Network tab of the browser's developer tools. There, you can see the outgoing request and what it comes back with.

    Bring up your form in the browser and fire off the click event. Then, find the request to 'getItem.php' and look at its response. If it's not what you expect, set getItem.php to echo 'hello' and die; if the network tab does not show 'hello' in the response, that means you're not hitting the endpoint. If you see 'hello', congratulations, you're close!

    In terms of your actual endpoint, I see you are repeatedly echoing the results of your query. This is not the most useful way to do this. Instead, json_encode the entire results set, echo that, and kill the script. This will return all your table rows as a JSON array which can then be read by javascript back on the client side.. I hope any of this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题