简体   繁体   English

如何在 Javascript 中发出异步 HTTP 请求?

[英]How do I make an asynchronous HTTP request in Javascript?

How do I asynchronously send a HTTP request with POST method and some variables to a page, like it was opened in a browser?如何使用 POST 方法和一些变量将 HTTP 请求异步发送到页面,就像在浏览器中打开一样?

I integrated my login system with my forum's, but, to complete the login, the user must be redirected to the forum and then back to the current page.我将我的登录系统与我的论坛集成,但是,要完成登录,用户必须被重定向到论坛,然后返回当前页面。 This is a kind of killer for my iPhone web app.这是我的 iPhone web 应用程序的杀手锏。

With this request I need to send some POST variables so the login can actually take place.有了这个请求,我需要发送一些 POST 变量,以便实际进行登录。 How do I do this in JavaScript and/or jQuery?如何在 JavaScript 和/或 jQuery 中执行此操作?

Edit : According to the jQuery AJAX library examples, this should work:编辑:根据 jQuery AJAX 库示例,这应该有效:

$.ajax({
    type: "POST",
    url: "/forum/ucp?mode=login",
    data:
    ({
        username : $("#username").first().val(),
        password : $("#password").first().val(),
        autologin : $("#autologin").first().val(),
        viewonline : $("#viewonline").first().val(),
        redirect : window.location
    }),
    success: function(msg)
    {
        location.reload();
    }
});

But guess what?但猜猜怎么了? It doesn't!它没有!

    $.ajax({
        type: "POST",
        url: "login.php",
        data: "user=bob&password=pass",
        success: function(data) {
            //function called when the server responds
        }
    }

Just use an XMLHttpRequest object.只需使用 XMLHttpRequest object。 This object is native to JavaScript.此 object 是 JavaScript 原生的。 There is plenty of instructions for this class on the web. web 上有很多关于这个 class 的说明。

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

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