Итак, для моего класса веб-дизайна меня попросил мой преподаватель научить простой JavaScript-код класса, и я хотел создать простой веб-сайт, который либо мой учитель, либо я мог бы использовать для этого. Я хотел, чтобы это было то, что (я думал, было бы просто), у которого был ящик для входа, и когда вы вошли в систему, если бы вы использовали мой логин или логин моего учителя, он работал бы, и он создавал бы кнопки или перенаправлял на другую страницу, на которой были кнопки на них, но по какой-то причине утверждение if else, которое я использую для входа (так как это только два экземпляра, в которых было бы правдой, не хочет работать.Javascript login redirect не работает
Редактировать : Я все еще изучаю Javascript и понимаю только его, чтобы преподавать некоторые из его основных частей (это все, что мне нужно для atm). Все, что я пытаюсь сделать, это заставить кнопки отображаться так, чтобы я мог тогда используйте их для вызова функций, которые создают информацию, которая выписана при нажатии. Так, например, чтобы создать кнопки, когда правильная информация для входа и затем, когда появятся появляющиеся кнопки, вы можете щелкнуть первый, и появится параграф о теге скрипта.
Существует не так много проблем с функциями проверки пароля и имени, которые работают, когда я делаю их обоими предупреждениями, причем первый из них является eeyup, если он прав и nnope, если информация не указана неправильно, обе они работают. Только тогда, когда я пытаюсь использовать document.write, я сталкиваюсь с проблемами.
* В настоящий момент происходит то, что кнопки, вспыхивающие на экране в течение секунды, затем исчезают, а окна входа/экран появляется снова. *
Функция Логин я использую:
<script type="text/javascript">
function validator(){
var name = document.KageForm.User.value;
var password= document.KageForm.pass.value;
if(password=="mypassword" && name=="myusername"|| password=="myteacherspassword" &&name=="myteachersname"){
document.write(showbuttons());
} else {
document.write("This is not meant for you to see.");
}}
</script>
Функция для отображения кнопок, showbuttons, выглядит следующим образом:
function showbuttons(){
document.write("<div><form><input type=\"button\" value=\"Starting Your Script\" onclick=\"FirstThingsFirst()\"/><br/><input type=\"button\" value=\"Learn about document.write\" onclick=\"writing()\" /><br/><input type=\"button\" value=\"Variables\"onclick=\"settingVariables()\" /><br/><input type=\"button\" value=\"Using Functions\" onclick=\"usingFunctions()\" /><br/><input type=\"button\" value=\"If Statements\" onclick=\"usingIfStatements()\" /><br/><input type=\"button\" value=\"Else Statements\" onclick=\"usingElseStatements()\" /><br/><input type=\"button\" value=\"Return to Login\" onclick=\"homepage()\" /></form></div>")
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
Общий код всей страницы это : (Также, если есть какие-либо неточности в тексте, которые вызывают кнопки, укажите их)
<!doctype html>
<html>
<head>
<style type="text/css">
body {background-image:url(https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg)}
body{
font-family:helvetica;
color:darkviolet;
}
h2 {color:darkviolet;}
#tag1 {width:480px;}
#wrapper { width:960px;margin:0 auto; }
}
div {
margin: 5px;
border: 5px solid darkviolet;
width:50%;
}
img {
width:20.00%;
height:20.00%;
}
ul li a {
margin: 10px;
padding: 2px;
background: #f2a7c6;
float: left;
border: 2px ;
}
a:link {text-decoration:none
color:darkviolet;}
h3 {
font-family:helvetica;
color:darkviolet
}
#white {
color:white;
}
</style>
<script type="text/javascript">
/*<input type=\"button\" value=\"Starting Your Script\" onclick=\"FirstThingsFirst()\"/><br/><input type=\"button\" value=\"Learn about document.write\" onclick=\"writing()\" /><br/><input type=\"button\" value=\"variables\"onclick=\"settingVariables()\" /><br/>input type=\"button\" value=\"Using Functions\" onclick=\"usingFunctions()\" /><br/>input type=\"button\" value=\"If Statements\" onclick=\"usingIfStatements()\" /><br/>input type=\"button\" value=\"Else Statements\" onclick=\"usingElseStatements()\" />*/
function FirstThingsFirst() {
var mytext = "<div id=\"thisshouldbewhite\"> To start writing Javascript into your page, you must first make use of the script tag. The tag is 'script' type=\"text/javascript\" with the closing tag simply being /script. you can use a Javascript either in your heading of your page, after the style tag, or anywhere in your body. Personally, I prefer to put all my script, or at least my functions, in the head of my page.</div> <input type=\"button\" value=\"Return to Home\" onclick=\"homepage()\" />"
document.write(mytext);
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function writing()
{
var mytext = "<div id=\"thisshouldbewhite\">To write something out on your screen, you use the command \'document.write()'. To get what you want to appear, put qutation marks around it in the paranthesis. So to write out \"bacon\", you would put: document.write(\"bacon\") in your script. Document.write() is used for many things, mainly displaying information based on input data given to the page by the user that fits into variables defined by the creator of the page. For example, document.write(variableX()) would print out anything that has been put in for variableX.</div><input type=\"button\" value=\"Return to Home\" onclick=\"homepage()\" />"
document.write(mytext);
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function settingVariables(){
document.write("<div id=\"thisshouldbewhite\">to create a variable, youtype in \'var\' followed by a space, then the name of the variable, an = then what the variable is equal to. So, if you had food on your mind and wanted your variable to be \'bacon\' your variable would be: var food=\"bacon\"</div><input type=\"button\" value=\"Return to Home\" onclick=\"homepage()\" />")
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function usingFunctions(){
document.write("<div id=\"thisshouldbewhite\">Functions are used to use commands only when triggered, or to do multiple things at once. for example, open up a website and type in the following code: <br/> <i>function troll(){<br/>document.write(\"gotcha!\");<br/>document.write(gotcha());<br/> function gotcha(){<br/>document.write(\" hahahaha!\");<br/>document.write(troll())</i>;<br/> What this will do is that the first function will call the second function, and then when the second function is called it will call the first function.Since neither are being called at the moment, create a button in your html as usual, but in the starting tag, add the property\"onClick\". Name your button something like, 'start trolling' or something like that. So, your code for your input should look something like <i><-input type=\"button\" value=\"Starting Your Script\" onclick=\"FirstThingsFirst()\"/></i> <br/> obviously minus the dash at the start of the tag.</br><input type=\"button\" value=\"Commence Trolling\" onclick=\"troll()\"/></div><input type=\"button\" value=\"Return to Home\" onclick=\"homepage()\" />");
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function usingIfStatements(){
document.write("<div id=\"thisshouldbewhite\">If statements are used to create scenarios such as login screens, since that is the use that will be most familiar to most of us. An If statement goes inside the function tag, so when in use the statement looks like this:<br/>function login(){<br/>if(conditions for if statement){commands for if statement to follow}}<br/> Here is an example of a functional function using an IF Statement:<br/>function login(){<br/>var name=\"your name\";<br/>if(name==\"your name\"){document.write(\"You are indeed yourself\")}}<br/>This would print out the words in the command following the If statement, since the statement is true, since the variable, \"name\" is equal to \"your name\"</div><input type=\"button\" value=\"Return to Home\" onclick=\"homepage()\" />");
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function usingElseStatements(){
document.write("<div id=\"thisshouldbewhite\">So, we know how to make an If statement, now we are going to use Else statements. This would be like on a login screen, if you type in inaccurate information and it gives you an error message<i><br/>function login(){<br/>if(conditions for if statement){commands for if statement to follow}else(commands for script to follow if your If statement is not true)}</i><br/> Here is an example of a functional function using an IF Statement:<i><br/>function login(){<br/>var name=\"your name\";<br/>if(name==\"your name\"){document.write(\"You are indeed yourself\")else{document.write(\"you are not yourself when you're hungry.\")}}}<br/></i></div>")
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
function troll(){
document.write("gotcha!");
document.write(gotcha());
}
function gotcha(){
document.write(" hahahaha!");
document.write(troll())
}
function homepage()
{
window.location.href = "file:///C:/Users/Admin/Documents/Websites/TEst.html";
}
function gotoButtons()
{
window.location.href = "file:///C:/Users/Admin/Documents/Websites/Buttons.html";
}
function showbuttons(){
document.write("<div><form><input type=\"button\" value=\"Starting Your Script\" onclick=\"FirstThingsFirst()\"/><br/><input type=\"button\" value=\"Learn about document.write\" onclick=\"writing()\" /><br/><input type=\"button\" value=\"Variables\"onclick=\"settingVariables()\" /><br/><input type=\"button\" value=\"Using Functions\" onclick=\"usingFunctions()\" /><br/><input type=\"button\" value=\"If Statements\" onclick=\"usingIfStatements()\" /><br/><input type=\"button\" value=\"Else Statements\" onclick=\"usingElseStatements()\" /><br/><input type=\"button\" value=\"Return to Login\" onclick=\"homepage()\" /></form></div>")
document.body.style.backgroundImage="url('https://fc04.deviantart.net/fs70/f/2013/029/6/8/smoke_by_kage_kaldaka-d5t50d9.jpg')";
document.getElementById('thisshouldbewhite').style.color="white";
document.getElementById('thisshouldbewhite').style.width="400px";
document.getElementById('thisshouldbewhite').style.fontFamily="helvetica";
}
</script>
</head>
<body>
<script type="text/javascript">
function validator(){
var name = document.KageForm.User.value;
var password= document.KageForm.pass.value;
if(password=="mypassword" && name=="myusername"|| password=="myteacherspassword" &&name=="myteachersname"){
document.write(showbuttons());
} else {
document.write("This is not meant for you to see.");
}}
</script>
<form name="KageForm">
Username:<input type="text" name="User">
<br/>
Password: <input type="password" name="pass">
<br/>
<input type="image" src="https://a.deviantart.net/avatars/k/a/kage-kaldaka.png?6"
value="Submit" onclick="validator()" />
<br/>
<input type="button" value="Starting Your Script" onclick="FirstThingsFirst()"/>
<br/>
<input type="button" value="Learn about document.write" onclick="writing()" />
<br/>
<input type="button" value="Variables"
onclick="settingVariables()" />
<br/>
<input type="button" value="Using Functions" onclick="usingFunctions()" />
<br/>
<input type="button" value="If Statements" onclick="usingIfStatements()" />
<br/>
<input type="button" value="Else Statements" onclick="usingElseStatements()" />
<br/>
<input type="button" value="" onclick="" />
<br/>
<input type="button" value="" onclick="()" />
<br/>
<input type="button" value="" onclick="()" />
<br/>
<input type="button" value="" onclick="()" />
</form>
</body>
</html>
Убедитесь, что у вас есть своего рода хеширование для пароля и сравнение хешей. То есть хранить хэш пароля и хешировать пароль при его вводе. Тогда сравните. Никогда не передавайте пароль в открытом виде, особенно если вы используете скрипт на стороне клиента, с которым могут взаимодействовать студенты. –
действительно не должен быть ответственностью JS за аутентификацию учетных данных .... вы работаете в изолированной программной среде intranet? это намерение проиллюстрировать подвиги? –
Крис, не могли бы вы подробнее рассказать о том, что это значит? Я все еще изучаю Javascript, я просто знаю достаточно, чтобы преподавать (очень) основные вещи в нем. Я еще не узнал о хэшах. Пароль, если быть честным, на данный момент, не является серьезной проблемой, потому что я сомневаюсь, что люди в моем классе смогут найти способ пообщаться с ним, так как они всегда висят и редко знают, что делать, как это есть, и 2, это просто то, что я хотел сделать там. Моя главная проблема заключается в том, что кнопки появляются, когда дается правильная информация для входа. Что вы можете предложить по этому поводу? –