douna2633 2016-02-21 17:17
浏览 48
已采纳

如果所有代码都在一个文件中,如何指定Ajax jquery url路径

I have issue with specifying the Ajax jQuery url path. I have one function contains all Html markup codes, php sned mail codes and Ajax jQuery code as follow

How i can specify url property in ajax code?

Info: i use wordpress theme and this function within my plugin directory

<?php
    function bsncontact() {

        //All php codes here
?>
        <form id="ajax-contact" class="navbar-form" action="" method="POST">
            <!-- other html markup codes -->
        </form>
        <script type="text/javascript">
            jQuery(function(){
            jQuery.ajax({
                type: 'POST',
                url: '',
                data: "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message,
                success: function(text) {

                }
           });
           });
       </script>
<?php
}
?>
  • 写回答

3条回答 默认 最新

  • drnrxv9383 2016-02-22 12:50
    关注

    As you say use wordpress theme. In wordpress theme this is very easy you can register ajax within your wordpress in backend(admin panel) and in front end of your theme

    First you may put your ajax code in separate (for example put ajax code within myajax.js file) and then put it within your js folder, and register the your ajax code (you create function and register these scripts within it) and wordpress admin ajax over your theme by using wp_localize_scrip

    function my_enqueue() {
        wp_enqueue_script( 'ajax-script', plugins_url( '/js/myajax.js', __FILE__ ), array('jquery') );
        wp_localize_script( 'ajax-script', 'ajax_object',array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
    }
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    

    Second put your HTML form code within separate function for example

    <?php
        function myhtmlfunc() {
            //Your html contact form here
            //not important if form contain action="", you can remove it
        }
    ?>
    

    Until now very easy.

    Third put your php sent mail code within another function and Ajax on the Viewer-Facing Side for bot logged and visitor users abs below AJAX in Plugins

    <?php
        function myphpmail() {
            //Put all php codes here
        }
        add_action( 'wp_ajax_my_action', 'myphpmail' );
        add_action( 'wp_ajax_nopriv_my_action', 'myphpmail' );
    ?>
    

    Fourth then set your ajax url as below

    $.ajax({
        type: 'POST',
        url:ajax_object.ajaxurl,
        success: function() {}
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元