问题
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.
- https://codex.wordpress.org/AJAX_in_Plugins
- 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