Ajax 在 wordpress 中调用 add current url

Ajax call add current url in wordpress

当我尝试在 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 调用失败。

对于任何 ajax 调用,您应该参考手抄本。

  1. https://codex.wordpress.org/AJAX_in_Plugins
  2. https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29

即使你没有运行它在插件中。

服务器端

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);
    }
);

在适当的设置下,您不想直接从您的主题文件夹中调用文件,最好有一个访问点,您可以加载您想要的文件和 return 适当的响应。

因为您缺少 location.protocol (http:)。 试试这个:

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