首页 文章

如何在WordPress get_header()之后将AJAX添加到页面

提问于
浏览
0

我有一个不属于WordPress的页面,除了我在WordPress库中调用get_header()和get_footer()以便将它包装在与其他页面相同的主题中 .

但是,在调用get_header()之后,如果我尝试调用任何类型的AJAX,它就会被忽略 . 这些块是否只需要添加到标头标签中,还是与WordPress有其他冲突?这是代码:

<?php
require_once( $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR."wp-config.php" );
global $current_user;
get_currentuesrinfo();
get_header();
global $wpdb;
?>

<script type="text/javascript">
<!--
$(function () {
    $('#AdminForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'post',
            url: 'ajax/save.php',
            data: $('#AdminForm').serialize();
            success: function () {
                alert('form was saved');
                }
            });
        });
    });
//-->
</script>

<form name="AdminForm" id="AdminForm">
<input type="submit" type="submit" value="Save" />
</form>

<?php
get_footer();
?>

我在Chrome开发者工具中发现以下错误:

未捕获的TypeError:$不是函数

有没有一种方法可以做到这一点,不会与WordPress发生冲突?

谢谢!

1 回答

  • 0

    这是由于Wordpress在no-conflict mode中使用了jQuery . 尝试设置如下:

    <script type="text/javascript">
    jQuery(function($) {
        $('#AdminForm').on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                type: 'post',
                url: 'ajax/save.php',
                data: $('#AdminForm').serialize();
                success: function() {
                    alert('form was saved');
                }
            });
        });
    });
    </script>
    

    现在,您可以将标准 $ 用于文档就绪功能中的所有功能 .

相关问题