javascript/ jquery/ document-ready
I'm learning jQuery but I have a problem.
Here the code:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = "text/javascript";
var pt = document.createElement('script');
pt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(pt);
$(document).ready(function() {
alert("ti vedo");
$.post('wait.php', function(data) {
alert("ti vedo2");
var dati = JSON.parse(data);
alert(data);
for (var i = 0; i <= dati.length; i++) {
var node = $(document.createElement("span"));
var content = $(document.createElement("div"));
var code = dati[i];
var text = $(document.createTextNode(code));
node.append(text);
content.append(node);
$("#boxMessage").append(content);
}
});
});
I use alert to check the error, but I can't see the first alert. So the problem is $(document)... but I don't understand why. I'm making a mistake when I include the jQuery library? Thank you for the Help!
You're getting the error because you're trying to access jQuery
(via $
) before it's available.
You can run your jQuery-related code after the script was really loaded:
var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.4.1.min.js'; script.type="text/javascript"; document.getElementsByTagName('head')[0].appendChild(script); script.addEventListener('load', function(){ alert("ti vedo"); $.post('wait.php',function(data){ alert("ti vedo2"); var dati=JSON.parse(data); alert(data); for(var i=0; i<=dati.length; i++){ var node=$(document.createElement("span")); var content=$(document.createElement("div")); var code=dati[i]; var text=$(document.createTextNode(code)); node.append(text); content.append(node); $("#boxMessage").append(content); } }); });
Also, you don't need two different versions of jQuery
simultaneously.
The order of activities is:
$
function is called, but $
is undefined, so the script terminates with an exception$
to the environment$
Use a regular <script>
element to load your dependencies instead of trying to load them half way through executing your script.
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.