php - 使用 MySQL 条目将按钮连接到 JavaScript 函数

标签 php javascript mysql html ajax

我在数据库中有一个表,我想使用 JavaScript 中的 XMLHttpRequest 将其渲染到 PHP 页面。我想将表中的每个条目呈现为 HTML 行/单元格,并在每个“条目”中有两个按钮。我想让条目中的每个按钮都调用一个特定的 JavaScript 函数来处理逻辑。

所以基本上,如果表中有 10 行,我将有 20 个按钮,每个按钮都会将一个参数传递给 2 个函数,具体取决于单击的按钮“类型”。

关于如何做到这一点有什么想法吗?

谢谢!

最佳答案

在您的服务器上,您需要一个 PHP 文件/操作来执行以下操作:

$return = array();
$q = mysql_query('SELECT * FROM ...');
while(($return[] = mysql_fetch_assoc($q)) !== false);
echo json_encode($return);

在预构建的 HTML 页面中,您需要一个用于打印数据的容器:

<div id="db-container"></div>

然后是该页面中包含的 JS(为了简单性和可读性,我在这里使用 jQuery,尽管您可以使用 native JS 或可能任何其他 JS 工具来完成此操作):

function getDB() {
  $.getJSON(
    'http://url.to/your/code.php',
    {},
    function(data) {
      var renderedHTML = '';
      /* parse the object representing PHP's $return, mainKey will be numerical keys */
      for(var mainKey in data) {
        /* one main loop iteration == one table row */
        renderedHTML += '<tr>'
        /* data[mainKey] is a row in DB, subKey will contain a name of a DB table column */
        /* data[mainKey][subKey] will therefore contain the value of DB table column 'subKey' for the DB table row numbered 'mainKey' */
        for(var subKey in data[mainKey]) {
          renderedHTML += '<td>' + data[mainKey][subKey] + '</td>'
        }
        /* statically add another HTML table column for the buttons */
        renderedHTML += '
          <td>
            <input type="button" name="b1" onclick="func1(\'arg1\')">
            <input type="button" name="b2" onclick="func2(\'arg2\')">
          </td>
        ';
        renderedHTML += '</tr>'
      }
      /* insert the built table into the page */
      $('#db-container').html('<table>' + renderedHTML + '</table>');
    }
  );
}

希望这有帮助。

关于php - 使用 MySQL 条目将按钮连接到 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12523519/

相关文章:

java - 使用 Jsoup 提交登录表单时出现问题

javascript - Highcharts 调整 y 轴以将 "100%"设置为自定义值的总和

mysql - 创建索引后查询速度很快,但几分钟后查询速度变慢 MySQL

MySQL 时间戳问题

javascript - 无法重现 Wordpress 4.2 持久 XSS 漏洞

php - 如何仅回显我的 $row 的索引

javascript - 将随机数存储在长度为 25 的数组中

php逻辑是使用if else条件还是多态

php - 如何在php中将页面重定向到https?

javascript - Greasemonkey 脚本注入(inject)