我开发了一个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使表单获取数据不是为了不断刷新整个页面而只是表单部分?
答案 0 :(得分:0)
<!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中查看