我正在尝试创建一个基于
AJAX的wordpress示例插件.我阅读了一个教程并做了一个插件,但它没有用.我是AJAX的新手.这是我试过的代码:
<?PHP class ajaxtest { function ajaxcontact() { ?> <div id="Feedback"></div> <form name="myform" id="myform"> <li> <label for fname>First Name</label><input type="text" id="fname" name="fname" value=""/> </li> <li> <label for lname>Last Name</label><input type="text" id="lname" name="lname" value=""/> </li> <input type="submit" value="Submit" id="submit" name="submit"/> </form> <script type="text/javascript"> jQuery('#submit').submit(ajaxSubmit); function ajaxSubmit() { var newcontact = jQuery(this).serialize(); jQuery.ajax({ type: "POST",url: "/wp-admin/admin-ajax.PHP",data: newcontact,success: function(data) { jQuery("#Feedback").html(data); } }); return false; } </script> <?PHP } function addcontact() { $fname = $_POST['fname']; if ($fname != "") { echo "Your Data is" . $fname; } else { echo "Data you Entered is wrong"; } die(); } } function jquery_add_to_contact() { wp_enqueue_script('jquery'); // Enqueue jQuery that's already built into wordpress } add_action('wp_enqueue_scripts','jquery_add_to_contact'); add_action('wp_ajax_addcontact',array('ajaxtest','addcontact')); add_action('wp_ajax_nopriv_addcontact','addcontact')); // not really needed add_shortcode('cform','ajaxcontact'));
wordpress环境
原文链接:https://www.f2er.com/php/136031.html首先,为了完成这项任务,建议注册然后将jQuery脚本排入队列,将脚本推送到服务器.这些操作将挂钩在wp_enqueue_scripts动作钩子中.在同一个钩子中,你应该把它用于包含任意JavaScript的wp_localize_script.通过这种方式,前端将有一个JS对象.该对象进行jQuery句柄使用的正确url.
请看看:
> wp_register_script();功能
> wp_enqueue_scripts勾
> @L_502_3@功能
> wp_localize_script();功能
add_action( 'wp_enqueue_scripts','so_enqueue_scripts' ); function so_enqueue_scripts(){ wp_register_script( 'ajaxHandle',plugins_url('PATH TO YOUR SCRIPT FILE/jquery.ajax.js',__FILE__),array(),false,true ); wp_enqueue_script( 'ajaxHandle' ); wp_localize_script( 'ajaxHandle','ajax_object',array( 'ajaxurl' => admin_url( 'admin-ajax.PHP' ) ) ); }
文件:jquery.ajax.js
jQuery(document).ready( function($){ //Some event will trigger the ajax call,you can push whatever data to the server,simply passing it to the "data" object in ajax call $.ajax({ url: ajax_object.ajaxurl,// this is the object instantiated in wp_localize_script function type: 'POST',data:{ action: 'myaction',// this is the function in your functions.PHP that will be triggered name: 'John',age: '38' },success: function( data ){ //Do something with the result from server console.log( data ); } }); });
最后,在你的functions.PHP文件中,应该有你的AJAX调用触发的函数.
记住后缀:
> wp_ajax(仅限注册用户或管理面板操作的功能)
> wp_ajax_nopriv(允许无特权用户的功能)
wp_ajax_myaction或wp_ajax_nopriv_myaction
add_action( "wp_ajax_myaction","so_wp_ajax_function" ); add_action( "wp_ajax_nopriv_myaction","so_wp_ajax_function" ); function so_wp_ajax_function(){ //DO whatever you want with data posted //To send back a response you have to echo the result! echo $_POST['name']; echo $_POST['age']; wp_die(); // ajax call must die to avoid trailing 0 in your response }