weixin_33694620 2015-01-24 13:25 采纳率: 0%
浏览 38

jQuery POST Ajax请求

i'm trying to post data from Server A, let's say: www.a.com to server B, www.b.com and then fetch the response from server B

I do it like this, this script runs on server A:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Naamloos document</title>
</head>

<body>

<form id="Form" onsubmit="validate();" method="post">
Email Address: <input type="text" id="email" name="email">
Password: <input type="text" id="password" name="password">
<input type="submit">
 </form>

<script>
function validate()
{
var e = $('email').value;
var p = $('password').value; //jQuery is easier to type
// the same as
// var p = document.getElementById('password').value;
var req = new Request({
    url: 'http://www.B.com/validate.php?',
    method: 'post',
    data: {'email' : e, 'password' : p},
    onComplete: function(response)
    {
        if (response == "Valid" ) 
        {
            alert("succes");
        }
        else
        {
            alert("blur");
        }
    }
}).send();
}
</script>

</body>
</html>

But at this moment, after hitting the submit button, the only thing that happends is that the fields are being cleared, thats all.

Validate.php looks like this:

<?php echo "Valid"; ?>
  • 写回答

2条回答 默认 最新

  • weixin_33693070 2015-01-24 13:29
    关注

    You're submitting the form, so the JavaScript never gets a chance to do anything significant. Since you haven't specified an action, it submits to the current URL and reloads the page.

    1. Stop using intrinsic event attributes.
    2. Use JS event binding (since you are using jQuery already, keep using it)
    3. Capture the event object and prevent the default behaviour of the submit event

    such:

    <form id="Form" method="post">
    
    $('#Form').on('submit', validate);
    
    function validate (event) {
        event.preventDefault();
        var e = $('#email').val();
    

    You also don't appear to have defined Request anywhere. You should probably switch to jQuery ajax


    Also note that Server B will have to give Server A permission to make Ajax requests to it using CORS.

    评论

报告相同问题?