简体   繁体   中英

Javascript (JQuery/CouchDB) function doesn't work but only when called from button onClick

In my HTML head I first include jquery.min.js, jquery.couch.js and twitter-bootstrap js (in that order) and then I have a function called logmein() as follows:

<script>
$.couch.urlPrefix = "http://127.0.0.1:5984"
function logmein() {$.couch.login({
    name: "testuser",
    password: "test",
    success: function() { alert("Success!") },
    error: function() { alert("Login failed") }
    });
}
</script>

With username and password hard-coded for testing.

I then have a button:

<button id="submit" class="btn btn-primary" onClick="logmein()">Sign in</button>

When I try and click submit, I get this error:

jquery.couch.js:216 TypeError: 'null' is not an object (evaluating 'resp.error')

However, if I type logmein() directly into Safari's web developer console, it works just fine! What am I doing wrong here?

Edit: I think it maybe related to this: https://stackoverflow.com/a/6792725/637562 though I don't quite understand why (to my knowledge, I was running it on the same protocol/host).

You can try changing your logmein function to run on the click event of #submit:

$('#submit').click(function(){
    $.couch.urlPrefix = "http://127.0.0.1:5984";
    $.couch.login({
        name: "testuser",
        password: "test",
        success: function() { alert("Success!") },
        error: function() { alert("Login failed") }
        });
});

Also, it seems that the urlPrefix should be inside the logmein() function

function logmein()
{
    $.couch.urlPrefix = "http://127.0.0.1:5984";
    $.couch.login({
        name: "testuser",
        password: "test",
        success: function() { alert("Success!") },
        error: function() { alert("Login failed") }
        });
}

"Solved"

If anyone else is having this issue, I'm still not exactly sure what caused the problem. Google Chrome gave a more detailed error message, suggesting the same origin policy had been violated, even though I don't believe this to be the case.

Despite this, there's a much simpler solution all without Javascript: the CouchDB Session API.

<form action="http://127.0.0.1:5984/_session/" method="post">
<input type="text" name="name">
<input type="password" name="password">
<button id="submit">Sign in</button>

Where 127.0.0.1 is a local couchdb instance, and should be replaced with your couchdb server address....

More details here: http://wiki.apache.org/couchdb/Session_API including how to set up automatic page redirection on form submission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM