wordpress中的ajax没有调用php函数

时间:2013-01-30 09:51:49

标签: php jquery ajax wordpress

想知道是否有人可以提供帮助;我正在尝试通过jquery将一些ajax实现到wordpress模板中的表单上。

jquery正在工作,我可以在sucess:部分中记录一个控制台消息,但数据是0,当它应该调用php函数时(此时在同一页面上,我可以调用它直接地)

所以我猜jquery正在运行,正在调用admin-ajax,它只是没有调用php函数。我有什么想法可能做错了吗?我不完全理解钩子,所以也许这是一个问题 - 我需要在某个地方挂钩?

jquery(域名将替换评论)

<script type="text/javascript">
    jQuery(function ($) {
        $( "#movies" ).autocomplete({
                minLength:2,
                delay:500,
                source: function( request, response ) {
                    $.ajax({
                        type: 'POST',
                        url: "http://<!--domain here -->/wp-admin/admin-ajax.php",
                        dataType: 'json',
                        data: {
                            action: 'getMoviesForCode',
                            searchString: $("#movies").val()
                        },
                        success: function( data ) {
                            response(data);
                            console.log('jjj'+data);
                        }
                    });
                }           
        });
    });
    </script> 

php函数(在同一页面上)

<?php

    function getMoviesForCode(){
echo "
        <script type=\"text/javascript\">
        alert(\"hh\");
        </script>
    ";
   $searchString = $_POST['searchString'];
   $results = va_getMoviesForCode($searchString);  
  $results = json_encode($results);
  die($results);
}
 ?>

谢谢,

1 个答案:

答案 0 :(得分:6)

你做错了。你的php函数应该在你主题的functions.php文件中。

然后,您应该将该功能挂钩到wp_ajax_[your_action]wp_ajax_nopriv_[your_action]

functions.php中的内容示例:

function getMoviesForCode(){
echo "
        <script type=\"text/javascript\">
        alert(\"hh\");
        </script>
    ";
   $searchString = $_POST['searchString'];
   $results = va_getMoviesForCode($searchString);  
  $results = json_encode($results);
  die($results);
}
add_action('wp_ajax_getMoviesForCode', 'getMoviesForCode');
add_action('wp_ajax_nopriv_getMoviesForCode', 'getMoviesForCode');