【问题标题】:On button click reload a php pull from mysql database without page reload在按钮上单击重新加载从 mysql 数据库中提取的 php,无需重新加载页面
【发布时间】:2016-01-29 19:46:44
【问题描述】:

我有一个 .php 页面,我在其中使用基于 cookie 值的 PHP 显示来自 MySQL 数据库的表。

在此页面上,无需重新加载页面,我可以通过单击按钮更改 cookie 数据:

$(document).ready(
function(){
    $(".button").click(function () {
        Cookies.remove('cookie');
        Cookies.set('cookie', 'value', { expires: 7 });

    });

});

如何在相同的单击功能中刷新 mysql SELECT,以便重新加载表内的数据而无需重新加载页面?

我的 php 数据在:

<div id="refresh-table"> <?php include 'pull-from.php'; ?> </div>

我已经阅读了所有我必须使用 AJAX 的地方 - 但我无法根据我经历过的所有帖子进行设置。我真的很感谢你的支持。

【问题讨论】:

  • $.get('pull-from.php', function(data) { $('#refresh-table').html(data); },基本上
  • 知道了!太感谢了!我浪费了3个小时。但是学习。

标签: javascript php jquery mysql ajax


【解决方案1】:

您需要在 pull-from.php 文件中添加一些代码(或创建另一个使用它来获取数据的文件),这些代码可以接受来自 AJAX 调用的参数并返回响应,最好是 JSON。这基本上就是您的网络服务。

下面是一个简单的例子,说明 php 基本上需要做什么。我包含了一个从 Web 服务获取数据并显示它的 html 页面。

<?php
$criteria = $_POST['criteria'];

function getData($params) {
    //Call MySQL queries from here, this example returns static data, rows      simulate tabular records.

    $row1 = array('foo', 'bar', 'baz');
    $row2 = array('foo1', 'bar1', 'baz1');
    $row3 = array('foo2', 'bar2', 'baz2');

    if ($params) {//simulate criteria actually selecting data
        $data = array(
            'rows' => array($row1, $row2, $row3)
        );

    }
    else {
        $data = array();
    }

    return $data;
}

$payload = getData($criteria);

header('Content-Type: application/json');//Set header to tell the browser what sort of response is coming back, do not output anything before the header is set.
echo json_encode($payload);//print the response 
?>

HTML

<!DOCTYPE html>
<html>
    <head>
    <title>Sample PHP Web Service</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">   </script>
<script>
    $(document).ready(function(){
        alert("Lets get started, data from the web service should appear below when you close this.");

    $.ajax({
        url: 'web-service.php',
        data: {criteria: 42},//values your api needs to query data
        method: 'POST',
    }).done(function(data){
        console.log(data);//display data in done callback
        $('#content').html(
        JSON.stringify(data.rows)//I just added the raw data
        );
    });

});

【讨论】:

  • 我已经检查了代码,实现并像魅力一样工作。这是我需要经历更多的事情。非常感谢您在这里提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2013-10-13
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
相关资源
最近更新 更多