个性化阅读
专注于IT技术分析

Ajax调用在WordPress中添加当前URL

点击下载

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


#1


对于任何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);
    }
);

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


#2


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

var path_test = location.protocol + '//' + document.location.hostname + '/wpcontent/themes/expression/imagecount.php';
赞(0)
未经允许不得转载:srcmini » Ajax调用在WordPress中添加当前URL

评论 抢沙发

评论前必须登录!