繁体   English   中英

使用AJAX调用Wordpress简码

[英]Call a Wordpress shortcode with AJAX

我在Wordpress中有一个简码,我想通过单击按钮使用jQuery来调用它。 我阅读了一些网站和教程,但是我无法确切知道会发生什么。

我把它放在function.php上:

add_action( 'init', function() { 
  ps_register_shortcode_ajax( 'ps_get_survey_form', 'ps_get_survey_form' ); 
} );

function ps_register_shortcode_ajax( $callable, $action ) {

  if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
    return;

  call_user_func( $callable );
}

function ps_get_survey_form() {
    echo do_shortcode( '[dopbsp id=6 lang=el]' );
    die(); 
} 

这是我在page-template.php上使用的:

<button id="testonclick" onclick="test()"></button>

<div id="testresults"></div>

<script>

function test() {
    jQuery.ajax({
        url: "http://localhost/myweb" + "/wp-admin/admin-ajax.php",
        data : {action: 'ps_get_survey_form'},
        success: function(results){
            jQuery("#testresults").html(results)
        },
        error: function(errorThrown){console.log(errorThrown);}
    });// end of ajax
}
</script>

但是,结果为0。知道发生了什么错误吗?

我相信您想使用类似

add_action('wp_ajax_nopriv_ps_get_survey_form', 'ps_get_survey_form' );
add_action( 'wp_ajax_ps_get_survey_form', 'ps_get_survey_form' );

而不是你的

add_action( 'init', function() { ps_register_shortcode_ajax( 'ps_get_survey_form', 'ps_get_survey_form' ); } );

您可以在此“法典”页面上阅读有关内容的更多信息。

据我所知,您编写的内容根本无法通过AJAX使用您的功能。 我当然不知道一切。 这只是我使用的方法。

您应该查看有关WP和AJAX的本文。 最好将ajax调用“绑定”到admin ajax脚本。

http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/

add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");

 wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/my_plugin/my_voter_script.js', array('jquery') );
   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

请注意,虽然短代码可能会加载表单所需的css或js,但不会通过ajax调用来加载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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