简体   繁体   中英

How do you use $('document').ready(function()) in jQuery?

I have a piece of code that is working fine in IE, but it doesn't run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function) . The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]. I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:

<html><head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
     /jquery.min.js"></script>
     <script type="text/javascript" language="javascript">
     $(document).ready(function() { 
     $.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
     $.each(jsonData, function (i, j) {
     document.form1.fruits.options[i] = new Option(j.options);
     });});
     });
     </script></head>
     <body><form name="form1">
     My favourite fruit is :
     <select name="fruits" id="fruits" /></form></body>
</html>

Short version (suggested by meeger): don't use single quotes around document.

document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.

$(document).ready(function() {

You'll also want to take the onLoad attribute off of the body tag, else it will run twice.

Just run $(document).ready(function() {doStuff}) . This will automatically run when the document is ready.

It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() { 
           $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
             var selectElem = $('#fruits');

             for(var i = 0; i < jsonData.length; i++) { 
               selectElem.append($('<option>').html(jsonData[i].options));
             }

           });
       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

EDIT: I tested with the following and mocked the json object since I can't make that call myself.

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
     <script type="text/javascript">
       $(document).ready(function() {
           var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
           var selectElem = $('#fruits');

           for(var i = 0; i < jsonData.length; i++) { 
             selectElem.append($('<option>').html(jsonData[i].options));
           }

       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

Here it is in all its glory. The shorthand, awesome version:

UPDATED

<script type="text/javascript" language="javascript">
    $(function() { 
        $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
            var cacheFruits = $('#fruits'),
                cacheOption = $(document.createElement('option'));

            $.each(jsonData, function (i, j) {
                cacheFruits.append(
                    cacheOption.clone().attr('value', j.options).html(j.options)
                );
            });
        });
    });
</script>

Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.

There should be no reason why the above would not work.

You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()

$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    $(this).each(jsonData, function (i, j) {
      document.form1.fruits.options[i] = new Option(j.options);
    });
  });
});

Try this, your json data should be in this format:

[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];


$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    var options = [];
    $.each(jsonData, function (i, j) {
      options.push('<option value="' + j.value + '">'  + j.text + '</option>');
    });
    $('#fruits').html( options.join(''));
  });
});

Please note that there may be an encoding/escaping issues here. Make sure that you escape the text properly from the server side. htmlentities, htmlspecialchars can help you with that.

This should work in most browsers

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