1

想知道是否有人可以提供帮助;我正在尝试通过 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);
}
 ?>

谢谢,

4

1 回答 1

6

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

You should then hook the function to wp_ajax_[your_action] and wp_ajax_nopriv_[your_action].

Example of what should be in your 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');
于 2013-01-30T10:02:29.747 回答