我好像错过了什么。下面共享的代码应该从选择框中获取值,通过Ajax将其传递给PHP函数,该函数将重新生成表数据并根据所选团队对其进行过滤。
我原以为这是一个简单的AJAX调用,但似乎我低估了创建这个jQuery的复杂性。
初始表单呈现,包括HTML表单(由PHP生成):
ob_start();
// Output the form
echo \' <form>\' .
\'Select a Team:\' .
\'<select name="select_team" onchange="fmsapi_refresh_hs()">\' .
\'<option value="">Full Schedule</option>\' .
\'<option value="4783">4783</option>\' .
\'<option value="2994">2994</option>\' .
\'</select>\' .
\'<div id="fmsapi_status"></div>\' .
\'</form>\';
// Start the div
echo \'<div id="frc_hybrid_table">\';
// Populate the table
frc_populate_hybrid_schedule($year, $event, $team);
echo \'</div>\';
//echo \'<h4>Raw Data:</H4><code>\' . $received_xml . \'</code>\';
// Store the output buffer before emptying it and returning it to the calling content.
$returnstring = ob_get_contents();
ob_end_clean();
return $returnstring;
下面是用于接收AJAX查询并将JS排队的代码:
function fmsapi_refresh_hybrid_schedule() {
// Collect the three variables from the POST parameters
$year = $_POST["year"];
$event = $_POST["event"];
$event = $_POST["team"];
return frc_populate_hybrid_schedule($year, $event, $team);
}
// Function to enqueue the script
function my_script_enqueuer() {
wp_register_script( "fmsapi_refresh_script", WP_PLUGIN_URL.\'/fmsapi/fmsapi_refresh_hybrid_schedule.js\', array(\'jquery\') );
wp_localize_script( \'fmsapi_refresh_script\', \'fmsapiAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' )));
wp_enqueue_script( \'jquery\' );
wp_enqueue_script( \'fmsapi_refresh_script\' );
}
add_action( \'wp_ajax_nopriv_fmsapi_refresh_hybrid_schedule\', \'fmsapi_refresh_hybrid_schedule\');
add_action( \'init\', \'my_script_enqueuer\' );
add_shortcode("frc_results", "frc_results");
最后,JS代码:
function fmsapi_refresh_hs() {
document.getElementById("fmsapi_status").innerHTML = "Query Triggered";
var data = {
action: \'fmsapi_refresh_hybrid_schedule\',
year: \'2017\',
event: \'ONOSH\',
team: \'4783\'
};
jQuery.ajax({
type: "post",
dataType: "json",
url: fmsapiAjax.ajaxurl,
data: data,
success: function (response) {
document.getElementById("frc_hybrid_table").innerHTML = response;
document.getElementById("fmsapi_status").innerHTML = data[\'event\'];
}
});
}
出于测试目的,我硬编码了团队编号,但我甚至无法让事件触发查询。我确信代码中充满了漏洞,但我甚至无法触发查询来开始调试其余部分。
最合适的回答,由SO网友:Drupalizeme 整理而成
Ajax调用中的操作必须是add_action
没有wp_ajax_nopriv.* 例如:
var data = {
action: \'fmsapi_refresh_hybrid_schedule\',
year: \'2017\',
event: \'ONOSH\',
team: \'4783\'
};
您的目标是名为
select_team 但这并没有出现在您的代码中。这就是为什么您的Js代码不能在更改操作中激发。
更改此行:
// Output the form
echo \' <form>\' .
\'Select a Team:\' .
\'<select name="select_team" class="select_team">\' .
您没有得到返回值,因为您只返回了一个字符串,而没有回显该字符串的值。
在函数中fmsapi_refresh_hybrid_schedule()
代替
return frc_populate_hybrid_schedule($year, $event, $team);
使用
echo frc_populate_hybrid_schedule($year, $event, $team);
exit;
还应该有
nonce field + 从中删除空间
add_action 还有更多的小问题,现在似乎已经断章取义了。