Почему не загружается скрипт?
Здравствуйте,
при загрузки главной страницы с формой выбора человека должен сработать присоединенный к файлу скрипт. И в частности в результате работы этого скрипта должна исчезнуть кнопка submit формы. Почему скрипт не загружается? Вот два файла - один страницы - другой - скрипт. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" » xml:lang="en" lang="en"> <head> <title>Ajax Address Book</title> <meta http-equiv="content-type" content="text/html; » charset=iso-8859-1" /> <meta http-equiv="Content-Language" content="en-us" /> <script type="text/javascript" src="XHConn.js"></script> <script type="text/javascript" src="addressBook.js"></script> </head> <body> <h1>Simple Ajax Address Book</h1> <form action="getAddress.php" method="POST"> <fieldset> <legend>Please Choose a Person</legend> <select id="person" name="person"> <option value="">Choose Someone</option> <option value="1">Bob Smith</option> <option value="2">Janet Jones</option> </select> <input type="submit" id="submit" name="submit" » value="Get the Address" /> </fieldset> </form> <pre id="address"></pre> </body> </html> addressBook.js var addressBook = { myConn: false, // the XMLHttpRequest body: false, // the body element target: false, // the target container loader: false, // the loader init: function(controlId, sbmtBtnId, targetId){ /* init() takes three arguments: * the id of the controller (select) * the id of the submit button * the id of the target container */ // test for methods & elements if(!document.getElementById || !document.getElementsByTagName || !document.getElementById(controlId) || !document.getElementById(sbmtBtnId) || !document.getElementById(targetId)) return; // set and test XHConn, quitting silently if it fails addressBook.myConn = new XHConn(); if(!addressBook.myConn) return; // get the body addressBook.body = document.getElementsByTagName('body')[0]; // get the controller var control = document.getElementById(controlId); // get the submit button var sbmtBtn = document.getElementById(sbmtBtnId); // remove the submit button sbmtBtn.parentNode.removeChild(sbmtBtn); // get the target addressBook.target = document.getElementById(targetId); // add the onchange event to the controller, addressBook.addEvent(control, 'change', function(){ if(this.value != ''){ /* if there's a value, trigger getAddress */ addressBook.getAddress(this.value); } else { // otherwise empty the target addressBook.target.innerHTML = ''; } }); }, getAddress: function(id){ // the Ajax call // let's let the user know something is happening (see below) addressBook.buildLoader(); /* this is the function that is run once the Ajax call completes */ var fnWhenDone = function(oXML) { // get rid of the loader addressBook.killLoader(); // insert the returned address information into the target addressBook.target.innerHTML = oXML.responseText; }; // use XHConn's connect method addressBook.myConn.connect('index.php', 'POST', 'id='+id, fnWhenDone); }, buildLoader: function(){ // builds a loader // create a new div addressBook.loader = document.createElement('div'); // give it some style addressBook.loader.style.position = 'absolute'; addressBook.loader.style.top = '50%'; addressBook.loader.style.left = '50%'; addressBook.loader.style.width = '300px'; addressBook.loader.style.lineHeight = '100px'; addressBook.loader.style.margin = '-50px 0 0 - 150px'; addressBook.loader.style.textAlign = 'center'; addressBook.loader.style.border = '1px solid #870108'; addressBook.loader.style.background = '#fff'; // give it some text addressBook.loader.appendChild( » document.createTextNode( » 'Loading Data, please wait\u2026')); // append it to the body addressBook.body.appendChild(addressBook.loader); }, killLoader: function(){ // kills the loader // remove the loader form the body addressBook.body.removeChild(addressBook.loader); }, addEvent: function(obj, type, fn){ // the add event function if (obj.addEventListener) » obj.addEventListener(type, fn, false); else if (obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() { obj["e"+type+fn](window.event); }; obj.attachEvent("on"+type, obj[type+fn]); } } }; /* run the init() method on page load, passing it the required arguments */ addressBook.addEvent(window, 'load', function(){ addressBook.init('person', 'submit', 'address'); }); |
ошибки какие-то появляются в консоли ошибок?
|
Нет. ничего нету. Вставил недавно этот скрипт в саму страницу и ничего не работает. Как проверить ошибки в джаваскрипте? Есть какоенибудь средство? А то код для меня очень сложный.
Спасибо |
для начала оформь код с помощью тэгов html, js (кнопки на панели инструментов) и сделай отступы - можно просто отредактировать первое сообщение
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" »
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" » xml:lang="en" lang="en"> <head> <title>Ajax Address Book</title> <meta http-equiv="content-type" content="text/html; » charset=iso-8859-1" /> <meta http-equiv="Content-Language" content="en-us" /> <script type="text/javascript" src="XHConn.js"></script> <script> var addressBook = { myConn: false, // the XMLHttpRequest body: false, // the body element target: false, // the target container loader: false, // the loader init: function(controlId, sbmtBtnId, targetId){ /* init() takes three arguments: * the id of the controller (select) * the id of the submit button * the id of the target container */ // test for methods & elements if(!document.getElementById || !document.getElementsByTagName || !document.getElementById(controlId) || !document.getElementById(sbmtBtnId) || !document.getElementById(targetId)) return; // set and test XHConn, quitting silently if it fails addressBook.myConn = new XHConn(); if(!addressBook.myConn) return; // get the body addressBook.body = document.getElementsByTagName('body')[0]; // get the controller var control = document.getElementById(controlId); // get the submit button var sbmtBtn = document.getElementById(sbmtBtnId); // remove the submit button sbmtBtn.parentNode.removeChild(sbmtBtn); // get the target addressBook.target = document.getElementById(targetId); // add the onchange event to the controller, addressBook.addEvent(control, 'change', function(){ if(this.value != ''){ /* if there's a value, trigger getAddress */ addressBook.getAddress(this.value); } else { // otherwise empty the target addressBook.target.innerHTML = ''; } }); }, getAddress: function(id){ // the Ajax call // let's let the user know something is happening (see below) addressBook.buildLoader(); /* this is the function that is run once the Ajax call completes */ var fnWhenDone = function(oXML) { // get rid of the loader addressBook.killLoader(); // insert the returned address information into the target addressBook.target.innerHTML = oXML.responseText; }; // use XHConn's connect method addressBook.myConn.connect('index.php', 'POST', 'id='+id, fnWhenDone); }, buildLoader: function(){ // builds a loader // create a new div addressBook.loader = document.createElement('div'); // give it some style addressBook.loader.style.position = 'absolute'; addressBook.loader.style.top = '50%'; addressBook.loader.style.left = '50%'; addressBook.loader.style.width = '300px'; addressBook.loader.style.lineHeight = '100px'; addressBook.loader.style.margin = '-50px 0 0 - 150px'; addressBook.loader.style.textAlign = 'center'; addressBook.loader.style.border = '1px solid #870108'; addressBook.loader.style.background = '#fff'; // give it some text addressBook.loader.appendChild( » document.createTextNode( » 'Loading Data, please wait\u2026')); // append it to the body addressBook.body.appendChild(addressBook.loader); }, killLoader: function(){ // kills the loader // remove the loader form the body addressBook.body.removeChild(addressBook.loader); }, addEvent: function(obj, type, fn){ // the add event function if (obj.addEventListener) » obj.addEventListener(type, fn, false); else if (obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() { obj["e"+type+fn](window.event); }; obj.attachEvent("on"+type, obj[type+fn]); } } }; /* run the init() method on page load, passing it the required arguments */ addressBook.addEvent(window, 'load', function(){ addressBook.init('person', 'submit', 'address'); }); </script> </head> <body> <h1>Simple Ajax Address Book</h1> <form action="getAddress.php" method="POST"> <fieldset> <legend>Please Choose a Person</legend> <select id="person" name="person"> <option value="">Choose Someone</option> <option value="1">Bob Smith</option> <option value="2">Janet Jones</option> </select> <input type="submit" id="submit" name="submit" » value="Get the Address" /> </fieldset> </form> <pre id="address"></pre> </body> </html> |
Цитата:
|
Цитата:
|
Цитата:
ты библиотеку xhconn подключил? |
Цитата:
Эта ж ветка не для продвинутых яваскрипачей! :cray: |
а надо быть продвинутым, чтобы скачать эту библиотеку с той же страницы?
|
таки нам нужны правило
и самое главное правило взять с наледа - "категорически запрещен идиотизм" |
Цитата:
|
кроме того, там в коде встречаются такие символы как », их надо поубирать
|
Цитата:
Спасибо большое!! Но я эту тему еще пока не закрываю. Вдруг какие-нибудь вопросы появятся. |
Почему не загружается скрипт?
Существует простой способ узнать, загрузился ли файл со скриптами. Называется "метод научного тыка", метод хорош тем, что не требует наличия и умения пользоваться отладчиком.
В файле, глобально, ставим алерт с любым текстом, если файлов несколько пишем так, чтобы было понятно какой именно файл выдал свой алерт, а какой не выдал. Жмём F5, и смотрим, есть загрузка или нет, если файл не загрузился, начинаем блокировать функции и жать F5, вычислив функцию, начинаем в ней отдельные строки блокировать. Вот так медленно, но точно находим дохлые строки из за которых не грузится целый файл. Это конечно не всё, на этой основе думайте головой. Или изначально пытайтесь понять, что же вам не русский отладчик пытается сказать. Сильно умные!, не надо про отладчики, вопрос очень спорный. Знал бы prog90 эту фигню раньше, не потерял бы прорву времени. |
Часовой пояс GMT +3, время: 07:39. |