通过ajax调用插件php文件

时间:2021-03-30 01:22:48

I wrote a wordpress plugin witch appends some comment functions in my template. Via ajax all the stuff should be transmitted into the wordpress database.

我写了一个wordpress插件,在我的模板中添加了一些注释功能。所有的东西都应该通过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.

getvar。php不知道wordpress环境,因为它是直接从用户提交调用的,我认为添加wordpress环境类和include不是很好的风格。

Is there any other way? Thanks for support.

还有别的办法吗?谢谢你的支持。

1 个解决方案

#1


9  

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
}

#1


9  

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
}