Using JQuery getJSON with other JavaScripts included gives ReferenceError

百般思念 提交于 2020-01-14 10:32:22

问题


I made a small example HTML page to get JQuery's getJSON method working. It looks like below (sorry for the sloppiness, this was just a proof of concept to then later add into a larger project):

<script type="text/javascript">

function test() {   
$.getJSON("http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=e999b3a5d47d013b780e8ac255c86266&user_id=24579658@N03&format=json&jsoncallback=?",    
                function(data){
                      $.each(data.photos.photo, function(i,photo){
     $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
    //alert();
        if ( i == 6 ) return false;
      });
});

}

I would then call that method when something was clicked using

<script type="text/javascript">

                            $(function() {
                                $("#yo").click(test);
                            });
    </script>

This worked fine in a project where the only JS I included was JQuery and these were the only functions. However, once I added it to my other project, it through errors. The other project has some mootools libraries included which I thought might've been doing it. However, even after completely removing the mootools stuff and just using this jquery stuff, I still get the error below:

ReferenceError: $ is not defined

I do have other javaScripts included such as a google one and some other ones I've made, but they don't use JQuery or Mootools. Can anyone explain why I'd be getting this error?


回答1:


It certainly sounds as if some of the additional code you have brought in has undefined the $ symbol. In fact, it is possible you have included some code that calls jQuery's noConflict function, which specifically undefines $.

jQuery, in essence, defines it like this:

$ = jQuery;

That means that you could replace the $ symbol in your code with "jQuery," for example:

jQuery.getJSON(...

or

jQuery(function() {
    jQuery("#yo").click(test);
});

Of course, the $ symbol shortcut certainly is handy. It would be a shame to give that up, so you could redefine it to stand in for "jQuery" once again. You would not want it to break any of your other, non-jQuery JavaScript, though, so the safe way to reestablish the $ shortcut would be to wrap all of your own code in closures. The lone parameter to each closure function would be "$" and the argument passed to each closure would "jQuery." For example:

(function($) {
        function test() {   
            $.getJSON("http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=e999b3a5d47d013b780e8ac255c86266&user_id=24579658@N03&format=json&jsoncallback=?",    
                        function(data){
                              $.each(data.photos.photo, function(i,photo){
             $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
            //alert();
                if ( i == 6 ) return false;
              });
        });
})(jQuery);

Notice that the anonymous function closure has the parameter $, so inside the entire function the $ will have the value you pass to the anonymous function. Next, notice that at the end of the function definition, we immediately invoke the function we have just defined and we pass jQuery as the argument. That means that inside the closure, but only inside the closure, $ is now a shortcut for jQuery.

One final note, you can deliberately turn off jQuery's use of the $ symbol by calling jQuery.noConflict() (see http://api.jquery.com/jQuery.noConflict/). If you will be using other JavaScript code beyond just your code and jQuery, it is a good idea to call that function after you have loaded all of your JavaScript files, then use the closure technique described above, so that you can safely continue to the $ shortcut in your own code.




回答2:


$ is not defined means that jQuery is not linked to the $ variable at the point of the error. This could be for one of two reasons:

  1. jQuery used to be set as the $ variable, but no longer is. You may have called jQuery.noConflict(), for instance.
  2. You have not yet defined jQuery. This may be because you have placed this script above the call to the jQuery library. Make sure that the first script you reference is the jQuery source.



回答3:


You have a conflict with the $ variable as mootools is also attempting to use the variable. Only 1 can use it at a time.

Check out jQuery.noConflict() -> http://api.jquery.com/jquery.noconflict/

You need to call no conflict before any attempt to use jQuery is made. You have a few optons with using jQuery.noConflict(). One is to just reassign and use a jQuery specific variable everywhere:

$jQ = jQuery.noConflict();

Now you can use $jQ

$jQ( "#yo" ).click( test );

When dealing with a separate JS file you can use a litte JS functionality to allow the '$' variable to mean "jQuery" within your file:

(function($) {
  function test() {   
  $.getJSON("http://api.flickr.com/services/rest/
  &method=flickr.people.getPublicPhotos&api_key=e999b3a5d47d013b780e8ac255c86266&user_id=24579658@N03&format=json&jsoncallback=?",    
                  function(data){
                        $.each(data.photos.photo, function(i,photo){
      $("<img/>").attr("src", "http://farm5.static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg").appendTo("#images2");
      //alert();
          if ( i == 6 ) return false;
        });
  });
})(jQuery);

That little beauty is called a self-invoking anonymous function. We are defining the $ as an input parameter, but passing in jQuery to ensure that is what the $ variable means.



来源:https://stackoverflow.com/questions/3822248/using-jquery-getjson-with-other-javascripts-included-gives-referenceerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!