How to Load Ajax in Wordpress

后端 未结 6 1921
失恋的感觉
失恋的感觉 2020-12-02 13:52

I\'m familiar with using ajax in the ordinary way with jQuery.
I\'ve played around it for a while, but don\'t understand what Wordpress needs to get it to work...
Wh

6条回答
  •  盖世英雄少女心
    2020-12-02 13:55

    Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

    1.in my htaccess file that lives in my wp-content folder i add this below what's already there

    
    Order Allow,Deny
    Allow from all
    
    

    In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

    2.) In my ajax code i can then use my url like this

    $.ajax({
        url:'/wp-content/themes/themeName/forms.php',
        data:({
            someVar: someValue
        }),
        type: 'POST'
    });
    

    obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

提交回复
热议问题