Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

javascript - window.location.href not working in form onsubmit

So i have a form, and onsubmit="return reg_check(this)" where reg_check() is a javascript function in the header which is supposed to check the form data, and since one of its tasks is to check if the username is in the database which requires php, i want to redirect to a php page that does this task.

Problem is: window.location.href is not working! Here's the function (reduced version) and of course the main.php is just a random page i got:

function reg_check(myForm) {
    alert("before redirect..");
    window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
    alert("after redirect..");
}

The before redirect and after redirect alerts work, it just doesn't redirect? It remains in the same page.

Also, if I tried to redirect from the body by just typing :

<script type="text/javascript">
    alert("before redirect..");
    window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
    alert("after redirect..");
</script>

it redirects.

Any ideas of how I could get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to return false; from your reg_check function and then in your onsubmit, change it to:

onsubmit="return reg_check(this);"

This will cancel the form submission. And if you want to let the form submit as normal, just return true from reg_check.

Edit (to be more clear you need to add return false; from your function):

function reg_check(myForm) {
    alert("before redirect..");
    window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
    return false;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...