简体   繁体   中英

Why has my jQuery + AJAX stopped working?

I'm fairly new to JavaScript/jQuery/AJAX, so I suspect the issue is some typo I'm not seeing. It was working fine, but at some point during editing the hide() + show() methods stopped working (tested it in Firefox + Chrome). I've pored over it many times and can't see what's wrong.

script.js

$(document).ready(function(){

    $('p').click(function() {
        $(this).hide();
    })

    $('#nav li a').click(function(){
        var toLoad = $(this).attr('href')+' #content';

        $('#content').hide('fast',loadContent);

        function loadContent() {
            $('#content').load(toLoad,'',showNewContent())
        }

        function showNewContent() {
                $('#content').show('normal');
        }
        return false;
    });
});

In my index.html page the following script includes are in the <head> section:

<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

You need to include jQuery before your script.js .

JavaScript code is executed synchronously. In your example, $ is (or at least should be) undefined , and of course undefined has no jQuery like methods.

Also, one of your callbacks is defined as showNewContent() . The parenthesis at the end will call that function and pass its results back as the callback, which is not what you want in this circumstance.

Instead, drop the () to pass just the reference to the function.

Change your index.html stuff to

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="script.js"></script>

and your code in script.js to:

$(document).ready(function(){

  $('p').click(function() {
    $(this).hide();
  })

  $('#nav li a').click(function(){
    var toLoad, loadContent, showNewContent; //keep the variable scope local
    toLoad = $(this).attr('href')+' #content';


    $('#content').hide('fast',loadContent);

    loadContent = function() {
        $('#content').load(toLoad,'',showNewContent)
    }

    showNewContent = function() {
            $('#content').show('normal');
    }
    return false;
  });
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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