首页 文章

Wordpress ajax发布到同一页面 - 只有管理面板访问权限

提问于
浏览
2

我只对wordpress站点有管理面板访问权限(没有文件级访问权限) . 我使用这个插件Shortcode Exec PHP添加php代码并将我的jquery添加到文本编辑器中 .

一切都很好 . 但是现在我想要一个ajax调用,其中我的ajax post url将是 window.location.href 并将指向我的短代码exec php if(isset($_POST)){ echo "Yes!" } 中的代码,我将整个页面作为响应 . 请注意,我是wordpress的新手,并使用草稿进行测试 .

请让我知道我做错了什么 . 赞赏关于实现这一目标的更好做法的建议 . 以下是我的代码:

// jQuery的

$.ajax(
                   {
                       type: 'POST',
                       url: window.location.href,
                       dataType: 'json',
                       cache: false,
                       data:{
                         action: 'test'
                       },
                       success: function(response)
                       {
                          alert('success');

                       },
                       error: function(xhr, textStatus, errorThrown)
                       {
                           alert('error');
                       }
                   });

// PHP

if(isset($_POST)){ echo "Yes!"; return "true"; }

谢谢 .

2 回答

  • 0
    The statndard way to interact with ajax in Wordpress through WP AJAX.You can do like this.
    
    $.ajax(
           {
               type: 'POST',
               url: "/wp-admin/admin-ajax.php?action=your_action_name",
               dataType: 'json',
               cache: false,
               data:{
                your data should be here
               },
               success: function(response)
               {
                  alert('success');
    
               },
               error: function(xhr, textStatus, errorThrown)
               {
                   alert('error');
               }
    });
    
    then in functions.php or plugin file you need to register a hook for ajax request.wp_ajax should be prefix your action hook name and then method for processing the request.
    
    add_action('wp_ajax','method_name');
    function method_name(){
    here is your code
    
    }
    
  • 0

    我认为你是客户端(JQuery) .

    但在wordpress中,您无法使用 isset 检查请求 .

    为此你必须这样实现:

    正如您在示例中声明的那样 test as action .

    //For example wp_ajax_**Your_Action**
    
        add_action( 'wp_ajax_test', 'test_callback' );
    
        function test_callback(){
          //implement your code     
        }
    

相关问题