【问题标题】:Ajax call add current url in wordpressAjax 调用在 wordpress 中添加当前 url
【发布时间】:2015-04-24 16:20:19
【问题描述】:

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

【问题讨论】:

  • 你在什么事件下运行这段代码?

标签: jquery ajax wordpress wordpress-theming


【解决方案1】:

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

  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';
    

    【讨论】:

    • @Abdul 有线,我已经重新测试过,看起来还可以。当您在 Firefox 或 Chrome 的“开发者工具”中查看“网络监视器”时会发送什么请求?
    猜你喜欢
    • 2019-11-30
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多