【问题标题】:PHP Form fetching MySQL using AJAX [duplicate]PHP表单使用AJAX获取MySQL [重复]
【发布时间】:2014-06-01 22:02:09
【问题描述】:

我开发了一个 php 表单,它根据下拉选项启动数据库请求以获取数据。

PHP 表单:

<form method="get" action="<?php echo $url = basename($_SERVER['PHP_SELF']); ?>">
<select name="town" onchange='this.form.submit()'> 
    <?php $result= mysql_query('Query'); ?> 
<option value="x" selected>Select Choice</option>
    <?php while($row= mysql_fetch_assoc($result)) { ?> 
        <option value="<?php echo htmlspecialchars($row['town']);?>" > 
            <?php echo htmlspecialchars($row['town']); ?> 
        </option> 
    <?php } ?> 
<input type="hidden" name="action" value="submit" /><br>
</select>
</form>

表单动作:

<?php
if(isset($_GET["action"])) { 

$var1= $wpdb->get_results("Query");
$var2= $wpdb->get_results("Query");

Content to show once executed }


 ?>

如何使表单使用 AJAX 获取数据而不是不断刷新整个页面而只刷新表单部分?

【问题讨论】:

  • “不要一直刷新页面?”你需要改一下,我不明白你的意思。
  • @Fred-ii- 现在对表单进行编码以获取重新加载整个页面所需的数据的方式,我不想重新加载整个页面以加快执行速度
  • 好吧,你可能应该use AJAX for that
  • 你尝试过 AJAX 吗?
  • 从文档开始:api.jquery.com/jQuery.ajax

标签: javascript php jquery mysql ajax


【解决方案1】:
<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <form id="form_id" action="<?php echo $url = basename($_SERVER['PHP_SELF']); ?>" method="post">
    <select id="town" name="town" onchange="send_to_server()"> 
<?php $result= mysql_query("Query"); ?> 
<option value="x" selected>Select Choice</option>
<?php while($row= mysql_fetch_assoc($result)){ ?> 
    <option value="<?php echo htmlspecialchars($row['town']); ?>"> 
        <?php echo htmlspecialchars($row['town']); ?> 
    </option> 
<?php } ?> 
<input type="hidden" name="action" value="submit" /><br>
</select>
 </form>
<script type='text/javascript'>
/* attach a submit handler to the form */
function send_to_server(){

var value = $("#town").val();

  /* get some values from elements on the page: */
  var $form = $("#form_id"); var url = $form.attr('action');

  /* Send the data using post */
  var posting = $.post( url, { option_value: $("#town").val() } );

  posting.done(function( data ) {
    alert('success');
  });
}
</script>
</body>
</html>

上面的内容正是你想要的。在 localhost 中检查它

【讨论】:

  • 您至少应该在 PHP_SELF 上进行 htmlentities 转换,因为这是一个已知的安全风险(跨站点脚本)。
  • @developers-have-no-vacation :我更专注于 AJAX 部分,因为提问者想要如何在不刷新页面的情况下获取值。无论如何感谢您的指出。
  • @MahasishShome 非常感谢您的代码和帮助!!!万分感激。显示带有 php 代码的 html 而不是 alert('success') 的最佳方法是什么?
  • @user3492795 如果要显示变量的值,则使用 echo in1.php.net/echo & 如果是数组,则使用 print_r in3.php.net/print_r 。如果满足您的需要,请考虑投票或接受答案。
  • @MahasishShome 问题是,据我所知,您无法将 php 代码直接集成到 javascript 代码中,这就是我问这个问题的原因,否则我可能错了?
猜你喜欢
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 2012-05-18
  • 2018-05-01
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多