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
547 views
in Technique[技术] by (71.8m points)

jquery - How to make Chrome remember password for an AJAX form?

I'm using AJAX for fast input validation on my login page. If everything is correct, the user is redirected.

Here's the code:

$(form).submit(function () {
    $.post($(this).attr('action'), $(this).serialize(), function (data) {
        if (data.status == 'SUCCESS') {
            window.location = data.redirectUrl;
        }
   }
...

It works really well in all browsers. But there's a problem in Chrome. It doesn't offer to save the password.

When JavaScript is turned off, the password is saved, so the problem is definitely in redirection to a new location.

How can I fix that?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I have found a dirty workaround for this problem, by inserting an invisible iframe and targeting the form to it:

<iframe src="/blank.html" id="loginTarget" name="loginTarget" style="display:none">
</iframe>

<form id="loginForm" action="/blank.html" method="post" target="loginTarget"></form>

The corresponding JavaScript:

$('#loginForm').submit(function () {
    $.post('/login', $(this).serialize(), function (data) {
        if (data.status == 'SUCCESS') {
            window.location = data.redirectUrl;
        }
    })
})

The trick is, that there are really two requests made. First the form gets submitted to /blank.html, which will be ignored by the server, but this triggers the password save dialog in Chrome. Additionally we make an ajax request and submit the real form to /login. Since the target of the first request is an invisible iframe the page doesn't refresh.

This is of course more useful if you don't want to redirect to another page. If you want to redirect anyway changing the action attribute is a better solution.

Edit:

Here is a simple JSFiddle version of it. Contrary to claims in the comment section, there is no reload of the page needed and it seems to work very reliably. I tested it on Win XP with Chrome and on Linux with Chromium.


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

...