jQuery Ajax似乎不起作用

Here is my HTML. Just a simple form:

<form>
    Username:
    <input type="text" id="username"/>
    <br/>
    Password:
    <input type="password" id="password"/>
    <br/>
    <input type="submit" id="submit" value="submit"/>
</form>

Here is my JS associated with it:

function init(){
$("#submit").click(function() {   
    var url = "http:example.com/mail";
    alert("what?");
    $.ajax(url, {
        type : 'post',
        data : {
            'username' : $("#username").val(),
            'password' : $("#password").val()
        },
        success : function() {
            alert("done");
        }
    });
});
}

After I clicked on the submit button, the $.ajax function is supposed to do a post to the URL where I keeps my server running.

However, from my server side log or firebug network monitoring, I didn't see any sign of the POST method. (The first alert was triggered but the second wasn't.)

They are two different applications that I developed, so after I did some research, here is one explanation:

Since $.ajax() uses XMLHttpRequest, it is subject to XHR's cross-domain restriction. Are your SiteA and SiteB on different hosts/ports? If so, you're seeing the expected behavior.

Is that so? If so, is there any workaround?

You need return false; at the end of the click handler to prevent the default submission of the form. Although once you prevent the form from submitting, you will still have the cross-domain restriction, which is not trivial to solve. Look into jsonp for a possible solution.

Change your event handler to this...

function init(){
$("#submit").click(function(event) {   
    event.preventDefault();

    var url = "http:example.com/mail";
    alert("what?");
    $.ajax(url, {
        type : 'post',
        data : {
            'username' : $("#username").val(),
            'password' : $("#password").val()
        },
        success : function() {
            alert("done");
        }
    });
});
}

This will stop the form from actually doing a full POST to the server.

I think this will work

function init(){

$("#submit").click(function(event) {
event.preventDefault();

var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
    type : 'post',
    data : {
        'username' : $("#username").val(),
        'password' : $("#password").val()
    },
    cache: 'false',
    async: 'false',
    success : function() {
        alert("done");
    }
});

}); }