Ajax测试(WordPress)

So, I have been struggling with making ajax work. Here is my previous question: AJAX (admin_url('admin-ajax.php');?action=) Not Found

Anyway, I decided to narrow down and only have necessary files.

Here is the set up.

test.php

  <div class="test">
       <a href="#test_demo" id="demo">Items</a>      
  </div>
  <div id="test_demo"> </div>  


<script>

  jQuery(document).ready(function() {
     jQuery('.test a').click(function(e) {
        e.preventDefault();

        var tab_id = jQuery('this').attr('id'); 


        jQuery.ajax({
            type: "GET",
            url: "<?php echo admin_url('admin-ajax.php'); ?>", 
            dataType: 'html',
            data: ({ action: 'test_tab', id: tab_id}),
            success: function(data){
                  jQuery('#test_' + tab_id).html(data);

        },
        error: function(data)  
        {  
        alert("Error!");
        return false;
        }  

        }); 

     }); 
     }); 


</script>

function.php

function test_tab_callback() {       
    $template_part_path = 'page-parts/test_' . $_GET['id'];
    get_template_part($template_part_path);
    exit;
 }
add_action('wp_ajax_test_tab', 'test_tab_callback');
add_action('wp_ajax_nopriv_test_tab', 'test_tab_callback');

test_demo.php

<div id="test_demo_content">Demo Content</div>

Here is the my idea on how it should work.

  1. test.php: When user clicks Items button, then the tab_idvariable in the jQuery saves the anchor id (in this case, it will be id="demo").
  2. Then admin-ajax.php is called.
  3. The saved id ("demo") is then passed onto the function.php and it is used in the variable $template_part_path = 'page-parts/test_' . $_GET['id']; which gives page-parts/test_demo for test_demo.php
  4. Then the template part is called and calledback to the jQuery.

  5. Then the data is "insert" into the jQuery('#test_' + tab_id).html(data); which is id="test_demo.

  6. The test_demo.php content should be displayed in the #test_demo div.

But it is not working. I used console.log(data) but showed no result. What am I doing wrong?

When your getting the jquery object of "this" you can't use the quotes. This was making tab_id as undefined and ruining the rest.

Here is what I mean:

http://jsfiddle.net/7r1dg7L4/2/

jQuery(document).ready(function() {
     jQuery('.test a').click(function(e) {
         e.preventDefault();
         var tab_id = jQuery(this).attr('id'); 
         alert(tab_id);
     });
});