Ajax调用在wordpress中添加当前url

时间:2015-04-24 16:20:19

标签: jquery ajax wordpress wordpress-theming

当我尝试在wordpress js文件中使用jquery执行ajax调用时,它会自动重定向到当前路径,然后附加我的自定义路径,以便我无法重定向我的真实URL。

这是我的代码:

var path_test = document.location.hostname + '/wpcontent/themes/expression/imagecount.php';
var path;
$.ajax({
   url: path_test,
  type: "GET",
  data: '30'
 }).done(function() {
    alert('ajax call success');
});

它添加路径,但首先添加当前URL然后添加我的URL,以便ajax调用失败。

2 个答案:

答案 0 :(得分:0)

对于任何ajax调用,您应该参考codex。

  1. https://codex.wordpress.org/AJAX_in_Plugins
  2. https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
  3. 即使您没有在插件中运行它。

    服务器端

    add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
    add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );
    
    function prefix_ajax_add_foobar() {
        // Handle request then generate response using WP_Ajax_Response
    
        // Here you would fetch and process desired file.
    }
    

    客户端

    jQuery.post(
        ajaxurl, 
        {
            'action': 'add_foobar',
            'data':   'foobarid'
        }, 
        function(response){
            alert('The server responded: ' + response);
        }
    );
    

    在正确的设置中,您不想直接从主题文件夹中调用文件,最好有一个访问点,您可以加载您想要的文件并返回正确的响应。

答案 1 :(得分:-1)

因为你错过了location.protocol(http :)。 试试这个:

var path_test = location.protocol + '//' + document.location.hostname + '/wpcontent/themes/expression/imagecount.php';