Ajax call add current url in wordpress

北战南征 提交于 2019-12-12 02:34:25

问题


When I am trying to perform an ajax call using jquery in wordpress js file, it automatically redirects to current path and then appends my custom path so I can't redirect my true URL.

Here is my code:

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

It adds path, but first adds current URL then adds my URL so ajax call fails.


回答1:


For any ajax calls you should refer to the codex.

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

Even though if you are not running it in a plugin.

Server-Side

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.
}

Client Side

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

In a proper setting u dont want to call files directly from your theme folder, its better to have a single access point which you can load the file u want and return a proper response.




回答2:


Because you're missing location.protocol (http:). Try this:

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


来源:https://stackoverflow.com/questions/29852610/ajax-call-add-current-url-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!