gpt4 book ai didi

javascript - WordPress自定义插件按钮onclick调用php函数

转载 作者:行者123 更新时间:2023-12-03 01:53:08 25 4
gpt4 key购买 nike

无论您在 WP 中放置占位符,我的插件都会显示 2 个输入字段和一个按钮。单击按钮后,它调用一个 js 函数,该函数应该使用 AJAX 启动一个 php 函数,但不知何故我收到错误消息:“引用错误 myAjax 未定义”

wsn-plugin.php

function wpb_new_company(){
echo '<input type="text" class="form-control" id="companyName" placeholder="Firmenname">';
echo '<input type="text" class="form-control" id="companyYear" placeholder="Jahr">';
echo '<button onclick="myAjax();" id="btnNewCompany" type="submit" class="btn btn-primary">Erstellen</button>';
}

script.js(处理所有事件)

function myAjax() {
alert("myAjax gestartet");
$.ajax({
type: "POST",
url: 'localhost/wp/wp-content/plugins/wsn-plugin/wsn-plugin.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}

});
alert("myAjax ausgeführt");
}

然后 wsn-plugin.php 应该运行一些函数

if($_POST['action'] == 'call_this') {
echo "i reached it";
}

已更改

function wpb_adding_scripts() {
wp_register_script('wsn_script', plugins_url('script.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('wsn_script');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

和js脚本:

function myAjax() {
alert("myAjax gestartet");
$.ajax({
type: "POST",
url: '/wp/wp-content/plugins/wsn-plugin/wsn-plugin.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}

});
alert("myAjax ausgeführt");
}

没有 chrome 显示错误消息:本地主机说
fatal error 未捕获错误调用wsn-plugin.php中未定义的函数add_action():16

最佳答案

听起来您没有使用 wp_register_script() 和 wp_enqueue_script() 从插件加载 JavaScript 文件。

编辑:这里还有其他问题,但我忽略了它们,因为它们不是导致错误的原因。您将需要阅读https://codex.wordpress.org/AJAX_in_Plugins并特别注意“单独的 JavaScript 文件”部分。这应该会让您将数据发送到正确的 URL 并能够处理它。

关于javascript - WordPress自定义插件按钮onclick调用php函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50340000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com