我想我已经快完成了,但尽管经过数小时的研究和反复试验,仍无法获得最终的作品。我在 WordPress 的页面上有一个表单,我希望用户能够根据表单输入运行数据库查询,然后显示下面的结果。据我所知,“最好”的方法是通过 Ajax。
我现在的位置:我编写了一个简单的 WordPress 插件,其中包含主 php 文件(systembuilder.php,位于默认插件文件夹中):
<?php
/**
* Plugin Name: System Builder
**/
function builder_init() {
wp_enqueue_script( 'builder-js', plugins_url( '/js/systembuilder.js', __FILE__ ));
}
add_action( 'wp_ajax_mriSearch', 'mriSearch' );
add_action( 'wp_ajax_nopriv_mriSearch', 'mriSearch' );
function mriSearch() {
global $wpdb;
$query = $_POST['query'];
$result = "Running mriSearch";
#$results = $wpdb->get_results( $wpdb->prepare($query, $inDate, $inMRILow, $inMRIHi) );
echo json_encode($result, true);
die();
}
和一个Javascript文件(systembuilder.js,位于插件下名为js的文件夹中):
<script>
$(document).ready(function(){
$('#MRISearchForm').submit(function(e){
e.preventDefault();
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(),
dataType: "json",
success:function(data){
// Process with the response data
$('#search_results').html(data);
}
});
});
});
</script>
Wordpress 页面上的表单:
<form type="post" action="/wp-admin/admin-ajax.php" role="form" id="MRISearchForm">
<p style="font-size: 16pt;">Date: <input style="font-size: 16pt;" type="date" name="inDate" width="200" height="32"></p>
<p style="font-size: 16pt;">Minimum MRI: <input style="font-size: 16pt;" type="number" name="inMRILow" value="70" min="0" max="100" width="200" height="32"></p>
<p style="font-size: 16pt;">Maximum MRI: <input style="font-size: 16pt;" type="number" name="inMRIHi" value="100" min="0" max="100" width="200" height="32"></p>
<input type="hidden" name="action" value="mriSearch"/>
<input type="submit" name="submit" value="Search" style="font-size: 18pt;">
<input type="reset" style="font-size: 18pt;">
</form>
<div id="search_results"></div>
我还没有编写任何数据库查询等,只是想先让它工作。
提交表格后,我会看到一个空白页,上面写着“正在运行 mriSearch”。我似乎无法获取脚本来更新“search_results”div,而不仅仅是一个空白页面(网址为 ....com/wp-admin/admin-ajax.php?inDate=&inMRILow=70&inMRIHi=100&action= mriSearch&submit=搜索)。
我尝试将表单提交到我的插件 php,我尝试过使用空操作,我尝试过一百万次不同的事情,我确信这非常简单。
您应该在数据中使用
action:'mriSearch'
<script>
$(document).ready(function(){
$('#MRISearchForm').submit(function(e){
e.preventDefault();
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: {
action:'mriSearch',
postData: : form.serialize()
},
dataType: "json",
success:function(data){
// Process with the response data
$('#search_results').html(data);
}
});
});
});