Ajax无法在Wordpress中运行

时间:2012-03-14 21:01:50

标签: jquery ajax wordpress

希望有人可以帮助我。

我使用以下教程作为在wordpress http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

中运行ajax的指南

我的functions.php文件中有以下代码

wp_enqueue_script( 'my-ajax-request','/wp-content/themes/son-of-suffusion/js/ajax.js', array( 'jquery' ) ); 
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); 


/*AJAX STUFF*/

// this hook is fired if the current viewer is not logged in
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
 // if logged in:
do_action( 'wp_ajax_' . $_POST['action'] );


// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' ); 

function myajax_submit() {   

    echo 'ajax submitted';    

    die;

    // IMPORTANT: don't forget to "exit"  
    exit;

}

和我的ajax.js文件中的代码

// JavaScript Document

jQuery(function($){
   $(".selected").click(function () {

      alert("jQuery is working");
      $.post(MyAjax.ajaxurl, {
    action: 'myajax-submit',
      postID : MyAjax.postID

  }, function(response) {

     $("#content").html("loading...");
     $("#content").html(response);      


    });

     });


})

正在显示jQuery警报,但是ajax代码无法正常工作,整个页面会刷新。难道我做错了什么?当我使用Firebug时,我的js代码中没有错误。

提前谢谢

1 个答案:

答案 0 :(得分:2)

在您的点击功能中,传递如下所示的事件。并添加

  

ev.preventDefault

$(".selected").click(function (ev) {

  //prevents default action of the element
  ev.preventDefault();
  alert("jQuery is working");
  $.post(MyAjax.ajaxurl, {
  action: 'myajax-submit',
  postID : MyAjax.postID

  }, function(response) {

 $("#content").html("loading...");
 $("#content").html(response);      


});

 });