Ajax无法在Wordpress插件中运行

时间:2016-12-14 09:52:23

标签: ajax wordpress

我正在尝试为Wordpress插件构建一个具有Ajax功能的表单。正在调用jQuery函数,但没有显示任何响应。

这是 Ajax代码

function ajaxformschool() {
    var id = "Hello World";
    jQuery.ajax({
        type: 'POST',
        url: ajaxschoolajax.ajaxurl,
        action: 'ajaxschool_process',
        data: {"data":id},
        dataType: 'json',
        success: function(data) {
            alert(data);
            jQuery("#comment").html(data);
        }
    });
}       

前端并注册Ajax代码

function ajaxschool_enqueuescripts() {
    wp_enqueue_script('ajaxschool', ASSFURL. '/js/ajaxschool.js', array('jquery'));
    wp_localize_script('ajaxschool', 'ajaxschoolajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}

add_action('wp_enqueue_scripts', ajaxschool_enqueuescripts);
<form>
    echo '<a onclick="ajaxformschool();" style="cursor: pointer"><b>Search</b></a>';
    echo '<div id="comment"></div>';
</form>

Ajax功能操作

function ajaxschool_process() {
    $response="thanks everythong is ok";
    echo json_encode($response);
    die($response);
}

add_action( 'wp_ajax_nopriv_ajaxschool_process', 'ajaxschool_process' );
add_action( 'wp_ajax_ajaxschool_process', 'ajaxschool_process' );

3 个答案:

答案 0 :(得分:2)

您需要在jquery ajax函数的数据字段中添加action属性。

Ajax代码

jQuery.ajax({
        type: 'POST',
        url: ajaxschoolajax.ajaxurl,    
        data: {"data":id,'action':'ajaxschool_process'}, //MY CHANGE
        dataType: 'json',
        success: function(data) {
            alert(data);
            jQuery("#comment").html(data);
    }
    });

答案 1 :(得分:0)

以下是表单的HTML

<form type="post" action="" id="newCustomerForm">

<label for="name">Name:</label>
<input name="name" type="text" />

<label for="email">Email:</label>
<input name="email" type="text" />

<label for="phone">Phone:</label>
<input name="phone" type="text" />

<label for="address">Address:</label>
<input name="address" type="text" />

<input type="hidden" name="action" value="addCustomer"/>
<input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>

接下来,打开functions.php并添加以下行以确保在您的网站上加载jQuery:

wp_enqueue_script('jquery');
//The basic structure for writing an AJAX call is as follows:

function myFunction(){
//do something
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');

最后是javascript代码:

<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);

function ajaxSubmit(){

var newCustomerForm = jQuery(this).serialize();

jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: newCustomerForm,
success:function(data){
jQuery("#feedback").html(data);
}
});

return false;
}
</script>

答案 2 :(得分:0)

为了澄清,不需要同时echoexit(或die),因为exitdie都会回应出来的回应。我已经对Ajax流程函数进行了重要更改......

function ajaxschool_process() {
    $response = "Thanks. Everything is ok.";
    exit(json_encode($response));
}