简体   繁体   English

Wordpress:通过ajax调用插件php文件

[英]Wordpress: call to plugin php file via ajax

I wrote a wordpress plugin witch appends some comment functions in my template. 我写了一个wordpress插件女巫在我的模板中添加了一些评论功能。 Via ajax all the stuff should be transmitted into the wordpress database. 通过ajax,所有的东西都应该传输到wordpress数据库。

The problem is - the ajax handler needs a php file with captures the query via 问题是 - ajax处理程序需要一个php文件来捕获查询

if(isset($_POST['name'], $_POST['title'], $_POST['description'])) { 

 // do something with wordpress actions, e.g. get_current_user, $wpdb

}

At the time the user transmits the query the ajax handler calls the php file like this: 在用户传输查询时,ajax处理程序调用php文件,如下所示:

$('#ajax_form').bind('submit', function() {
    var form = $('#ajax_form');
    var data = form.serialize();
    $.post('../wp-content/plugins/test/getvars.php', data, function(response) {
        alert(response);           
    });
    return false; 

The getvars.php doesn't know the wordpress environment because it is called directly from user submit and I think to add the wordpress environment classes and includes is not the good style. getvars.php不知道wordpress环境,因为它是直接从用户提交调用的,我认为添加wordpress环境类并包含不是好的风格。

Is there any other way? 还有其他方法吗? Thanks for support. 感谢你的支持。

yes use the builtin wordpress ajax actions: 是的使用builtin wordpress ajax动作:

your jquery will look like this: 你的jquery看起来像这样:

$('#ajax_form').bind('submit', function() {
    var form = $('#ajax_form');
    var data = form.serialize();
    data.action = 'MyPlugin_GetVars'
    $.post('/wp-admin/admin-ajax.php', data, function(response) {
        alert(response);           
    });
return false; 

your plugin code something like: 你的插件代码如下:

add_action("wp_ajax_MyPlugin_GetVars", "MyPlugin_GetVars");
add_action("wp_ajax_nopriv_MyPlugin_GetVars", "MyPlugin_GetVars");

function MyPlugin_GetVars(){
    global $wpdb;
    // use $wpdb to do your inserting

    //Do your ajax stuff here
    // You could do include('/wp-content/plugins/test/getvars.php') but you should
    // just avoid that and move the code into this function
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM