简体   繁体   中英

what is home_url() equivalent in Javascript?

I am studying Wordpress with some ajax function. My problem is the PATH in my request is in hardcoded is there any function for this? And I can't get the root folder in my site.

Here's my code and it returns an error because my path is incomplete:

$.post(document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php', {action: 'zwap_add_wishlist', postId: 100}, function(response){
    alert(response);
});

And I got this URL:

http://localhost/wp-admin/admin-ajax.php

My problem is my wordpress is in this URL:

http://localhost/wp/wordpress_tutorial/

I know the function ajaxurl() but I can't apply it because my file is in javascript

These should do it.

 var base_url = window.location.origin; var host = window.location.host; var pathArray = window.location.pathname.split( '/' ); 

or this

 var getUrl = window.location; var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1]; 

A global variable ajaxurl is defined in the admin header to be used in ajax call since WP 2.8.

For more information: http://codex.wordpress.org/AJAX_in_Plugins

just use inbuild functionality

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {

   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );

}

then your url will available in myAjax.ajaxurl

and you can use

$.post(myAjax.ajaxurl, {action: 'zwap_add_wishlist', postId: 100}, function(response){
    alert(response);
});

try this and let me know if it is working here is the refrence refrence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM