wordpress - Yet another WordPress Ajax 400 Bad Request problem
问题描述
I am certain I am making a basic mistake here. I am getting the lovely 400 Bad Request response from WordPress when I try to make an Ajax call. I have one Ajax call that works, and this one that does not. I have looked at several posts both here and elsewhere, but remain stumped as to where I have erred.
Okay, the relevant code. First, here is how I do the add_action and script registration:
if ($_GET["page"] == "krudkat_data_structures") {
add_action("wp_ajax_krud_save_new_connection", "krud_save_new_connection");
}
// Other Stuff, for the Ajax call that works.
if ($_GET["page"] == "krudkat_data_structures") {
wp_register_script("krud_data_structures", plugin_dir_url( __DIR__ ) . "/js/dataStructures.js", array("jquery"));
wp_localize_script("krud_data_structures", "krudAjax", array( "ajaxurl" => admin_url("admin-ajax.php")));
wp_enqueue_script("krud_data_structures");
}
This sits in a function outside of a class. My JS call is like this:
var krudNewConnect = { action:"krud_save_new_connection",
dbname:$("#krud_new_dbname").val().trim(),
dbhost:$("#krud_new_dbhost").val().trim(),
dbconnect:$("#krud_new_dbconnect").val().trim(),
dbusername:$("#krud_new_dbusername").val().trim(),
dbpassword:$("#krud_new_dbpassword").val() };
$.post(krudAjax.ajaxurl, krudNewConnect, function(newConnectData) {
console.log(newConnectData);
});
Finally, my PHP method is, thus far, very simple:
function krud_save_new_connection() {
$dbname = $_POST["dbname"];
$dbhost = $_POST["dbhost"];
$dbconnect = $_POST["dbconnect"];
$dbusername = $_POST["dbusername"];
$dbpassword = $_POST["dbpassword"];
$dbport = 0;
$dbsocket = '';
if (!empty($dbconnect)) {
if (is_numeric($dbconnect)) {
$dbport = $dbconnect * 1;
} else {
$dbsocket = $dbconnect;
}
}
echo "Port: " . $dbport . "\nSocket: " . $dbsocket;
wp_die();
}
This is not expected to work when somebody is not logged in as an admin, so I omitted the no_priv add_action. I am certain this is not the problem; I did add that into my code and it had no impact.
What newbie mistake have I made? :)
解决方案
首先,将脚本排入队列,然后为 ajax 本地化脚本。它将解决问题。检查法典:https ://codex.wordpress.org/AJAX_in_Plugins
推荐阅读
- python - 在我的网格布局中绘制到许多坐标系,然后使用 seaborn 和 mathplotlib 绘制
- excel - 如何从Excel中的数字中获取第一个有效数字?
- android - 编译 native_app_glue.c 导致库文件无效
- python-3.x - 基于条件的 Pandas 窗口平均值
- java - Java 系统独立的根目录路径
- azure-functions - 在消费计划下的 Azure 函数中使用 ServiceBusTrigger 时会出现延迟吗?
- unix - 我想从删除重复文件的文件中获取唯一数据
- github - 如何在 Visual Studio 上刷新 Github 项目
- python - 如何在保留最后一个索引的同时反转列表?
- c# - 如何让面板出现在镜头前