Dynamically loaded javascript doesn't work second time loaded

I am working on a webpage that uses a JQuery UI dialog (in modal mode) to display a form that is dynamically generated using Django. The basic flow is: - the user clicks a button - jquery (using AJAX) issues a get request that returns the html for the form which is then used to fill the dialog - The html contains a script tag that handles some UI on the form which loads fine and works as expected - the user than fills out the form and clicks "Done" and the form is submitted. The issue comes in when the user makes an error on the form. The server responds to the post request (that submits the form) with the original form (including the script) modified to show the errors. This second time the script is loaded it gets a "**Uncaught ReferenceError: $ is not defined (anonymous function)**" The script is exactly the same as before when it worked fine. To be clear throughout this entire process the page is never refreshed. Here is the gist of the javascript that takes care of the modal: var add_container = $("#add_container"); add_container.dialog({...}) function show_form(form,response_func) { add_container.html(form); add_container.dialog("open"); $("#add_form").submit(function (event) { return submit_form($(this),response_func); }); } function submit_form(form,response_func) { add_container.append('


'); //this is a trick to upload a file without reloading the page form.attr('target','upload_target'); $('#upload_target').load(function() { var response = $('#upload_target').contents().find('body').html(); add_container.dialog("close"); resp_obj = $(response) if (resp_obj.is('form')) { //***this is what reloads the form when there is an error show_form(response,response_func); } else { response_func(resp_obj); } }); } $('#add_link').click(add_link); function add_link() { $.get('/add_link', function(data) { function add_response(response) { //handle successful submission } show_form(data,add_response); }); } //...more stuff that is not important This is the gist of the html returned from /add_link
The add_form.js is a pretty standard javascript file that uses jQuery. Its starts with $(document).ready(function () {...} ) and the first $ is where the ReferenceError occurs The form needs to be dynamically generated based on what is clicked so I can't just put everything statically on the page. The script is not dynamically generated so it doesn't necessarily need to be dynamically loaded but I wasn't sure how to keep it in its own file, and also only have it run when the form is loaded. I am open to suggestions of alternative ways to accomplish the same effect.

以上就是Dynamically loaded javascript doesn't work second time loaded的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准