ajax无法在header.php中工作


ajax not working in header.php

我正在WordPress中学习Ajax,并参考了一些教程。现在,我已经制作了这个Ajax脚本,它的表单很简单,有名称字段。我在header.php文件中调用这个脚本。实现后,我得到了0。为什么以及如何修复它。有人能告诉我为什么会发生这种事情吗。

我的代码:

<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit(){
    var newCustomerForm = jQuery(this).serialize();
        $.ajax({
            type:"POST",
            url: "http://localhost/woocommerce/wp-admin/admin-ajax.php",
            data: newCustomerForm,
            success:function(data){
                $("#feedback").html(data);
            },
            error: function(errorThrown){
                alert(errorThrown);
            }  
        });
        return false;
}

如果有人指导我,我将不胜感激:)

谢谢。

将其添加到您的ajax调用中

action  : 'search_action',
url: "http://localhost/woocommerce/wp-admin/admin-ajax.php",
data: newCustomerForm,

如果ajax请求进入,wordpress将调用whitch函数:

function ajax_handler() {
    $response = array( 'status' => 'error' );
    // do your thing here
    // $_POST is available
    // and and something like $response['text'] = 'all done'; or so
    $response['status']     = 'success';

    header( 'Content: application/json' );
    echo json_encode( $response );
    die;
}
add_action( 'wp_ajax_search_action', 'ajax_handler' );
add_action( 'wp_ajax_nopriv_search_action', 'ajax_handler' );

正如您所看到的,一个操作是为已登录用户调用的,另一个操作为未登录用户调用(wpajaxnopriv_searchaction)。在这种情况下,这两个操作调用相同的函数。

点击此处阅读更多信息:http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

$ 替换所有jQuery

更新:您仍未将所有jQuery更改为$更改:

jQuery('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit(){
    var newCustomerForm = jQuery(this).serialize();

至:

$('#newCustomerForm').submit(ajaxSubmit);
function ajaxSubmit(){
    var newCustomerForm = $(this).serialize();