简体   繁体   English

jQuery POST Ajax请求

[英]jQuery POST Ajax request

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 我正尝试将数据从服务器A发布,例如:www.a.com到服务器B,www.b.com,然后从服务器B获取响应

I do it like this, this script runs on server A: 我这样做,此脚本在服务器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: Validate.php看起来像这样:

<?php echo "Valid"; ?>

You're submitting the form, so the JavaScript never gets a chance to do anything significant. 您正在提交表单,因此JavaScript永远没有机会做任何重要的事情。 Since you haven't specified an action , it submits to the current URL and reloads the page. 由于您尚未指定action ,它会提交到当前URL并重新加载页面。

  1. Stop using intrinsic event attributes. 停止使用内部事件属性。
  2. Use JS event binding (since you are using jQuery already, keep using it) 使用JS事件绑定(因为您已经在使用jQuery,请继续使用它)
  3. Capture the event object and prevent the default behaviour of the submit event 捕获事件对象并阻止Submit事件的默认行为

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. 您似乎也没有在任何地方定义“ Request You should probably switch to jQuery ajax 您可能应该切换到jQuery ajax


Also note that Server B will have to give Server A permission to make Ajax requests to it using CORS. 还要注意,服务器B将必须授予服务器A使用CORS对其进行Ajax请求的权限。

Try to replace this 尝试取代这个

var e = $('email').value;
var p = $('password').value;

with this 有了这个

var e = $('#email').val();
var p = $('#password').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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