简体   繁体   English

如何正确发送POST数据?

[英]How to properly send POST data?

I am trying to use AJAX to improve my login system to run without refreshing the page. 我正在尝试使用AJAX来改进我的登录系统,以使其运行而无需刷新页面。 I'm quite new to ajax. 我对ajax很陌生。 The tutorials I've found all use GET. 我发现所有教程都使用GET。 I don't want to use get. 我不想使用get。 Here is my code: 这是我的代码:

login.php (I removed the CSS code from this) login.php(我从中删除了CSS代码)

<html>
<script type="text/javascript" src = "login/loginJS.js"></script>
    <body>
    <center>
        <div class="rounded">
        <form method='POST' action = "processLogin.php">
            Username:<input type="text" class = "input1" name = "username"/><br>
            Password:<input type="password" class = "input1" name = "password"/><br>
            Remember Me?<input type="checkbox" name = "remember"/?><br>
            <?php
            session_start();
            echo'<p id="errorField" class="error"></p>';
            ?>
            <input type="submit" value = "Login" class = "button" onclick='process()'/>
            <b><p>New User? <a href="register.php">Register</a></p></b>
        </form>
        </div>
    </center>
    </body>
</html>

loginJS.js loginJS.js

xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject()
{
    var xmlHttp;

    if (window.ActiveXObject){
        try{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
        xmlHttp = false;
        }
    }else{
        try{
            xmlHttp = new XMLHttpRequest();
        }catch(e){
            xmlHttp = false;
        }
    }

    if(!xmlHttp){
        alert("The XML Http Request Failed");
    }else{
        return xmlHttp;
    }
}

function process(){
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
        login = encodeURIComponent(document.getElementById("loginField").value);
        xmlHttp.open("POST", "login/processLogin.php",true);
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send();
    }else{
        setTimeout('process()',1000);
    }
}

function handleServerResponse(){
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById("errorField").innerHTML = message;
        }
    }
}

processLogin.php processLogin.php

      <?php
    session_start();
    header('Content-Type: text/xml');
    echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
    echo "<response>";
        $username = $_POST['username'];
        $password = $_POST['password'];
        if ($username == '' or $password == '')
        {
            echo 'The username/password fields may not be blank.';
        }else{
            echo 'This is a test';
        }
    echo "</response>";
?>

So my question is, what should I do to take the variables inside the input text and password field, to put as a post variable, then to send it with the javascript. 所以我的问题是,我应该怎么做才能在输入文本和密码字段中获取变量,将其作为post变量,然后使用javascript发送。 I just need to send the username and password fields. 我只需要发送用户名和密码字段。 To see the website, http://rukiryo.bugs3.com That is what the website looks like. 要查看该网站,请访问http://rukiryo.bugs3.com The login button works when I use my page-refresh method, but I can't figure out the last steps to make it work for non-refresh. 当我使用页面刷新方法时,登录按钮可以使用,但是我无法弄清楚使其不刷新时可以使用的最后步骤。

Thanks, Alex 谢谢,亚历克斯

Well in the above code you don't seem to be sending the login parameters with the AJAX Request. 在上面的代码中,您似乎并没有使用AJAX请求发送登录参数。 Also you forgot to explicitly set to Content-type header, which is necessary when doing POST requests. 另外,您还忘记了显式设置为Content-type标头,这在执行POST请求时是必需的。

    xmlHttp.open("POST", "login/processLogin.php",true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send();  // <--This is your problem

Your posting a blank send with no parameters 您发布的空白发送没有参数

Here's how you add parameters 这是添加参数的方式

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  
xmlhttp.send("username=carl&password=XYZ");

Obviously you will have to url encode these parameters so use this (so that things like +,* etc. don't show up in the URL and ruin your life) 显然,您将必须对这些参数进行url编码,因此要使用它(这样,+,*等内容就不会出现在URL中并破坏您的生活)

var params= "username="+encodeURIComponent("carl")+"&password="+encodeURIComponent("XYZ");
xmlhttp.send(params);

Oh and on the PHP side you should run urldecode to get back your strings 哦,在PHP方面,您应该运行urldecode取回您的字符串

Ok, here goes the long winded, plain ol' vanilla JavaScript way of doing it. 好的,这是漫长而简单的原始JavaScript方式。 I'm going to assume that you need support for < IE6 so first thing would be to do a check for which xhr object the browser supports. 我将假设您需要对<IE6的支持,所以第一件事就是检查浏览器支持哪个xhr对象。

function createXHR() {
    if (typeof XMLHttpRequest !== "undefined") {
        return new XMLHttpRequest();
    } else {
        var versions = ["MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.3.0"];

        for (var i = 0, len = versions.length; i < len; i++) {
            try {
                var xhr = new ActiveXObject(versions[i]);
                return xhr;
            } catch (e) {
                // do nothing
            }
        }
    }
    return null;
}

Next thing is to attach the onsubmit event handler to the form. 下一步是将onsubmit事件处理程序附加到表单。 Here is where jQuery is great with dealing with non DOM compliant browsers. jQuery非常适合处理不符合DOM的浏览器。 Trying not to be to verbose, here is a short way to account for this. 尽量不要太冗长,这是解决此问题的一种简短方法。

var form = document.form[0];

function addEventListener(el, evt, fn) {
    if (typeof addEventListener === "function") {
        el.addEventListener(evt, fn, false);
    } else {
        e.attachEvent("on" + evt, fn);
    }
}

Then add onclick event handler and pass in the function you want called on the submit: 然后添加onclick事件处理程序,并在提交时传入您要调用的函数:

addEventListener(form, 'click', process);

Before I dive into the process function, I would create a function that serializes the form fields. 在深入研究流程功能之前,我将创建一个将表格字段序列化的功能。 Here is one that I use: 这是我使用的一个:

function serialize(form) {
var parts = [],
    field = null,
    i,
    len,
    j,
    optLen,
    option,
    optValue;

for (i = 0, len = form.elements.length; i < len, i++) {
    field = form.elements[i];

    switch(field.type) {
        case "select-one":
        case "select-multiple":

            if (field.name.length) {
                for ( j = 0, optLen = field.options.length; j < optLen; j++) {
                    option = field.options[j];
                    if (option.selected) {
                        optValue = "";
                        if (option.hasAttribute) { //DOM compliant browsers
                            optValue = (option.hasAttribute("value") ? 
                                option.value : option.text);
                        } else {
                            optValue = (option.attributes["value"].specified ? 
                                option.value : option.text);
                        }
                        parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
                    }
                }
            }
            break;

        case undefined: //fieldset 
        case "file":    //file input
        case "submit":  //submit button
        case "reset":   //reset button
        case "button":  //custon button
            break;

        case "radio":    //radio button
        case "checkbox": //checkbox
            if (!field.name) {
                break;
            }
            /* falls through */

        default: 
            //don't include form fields without names
            if (field.name.length) {
                parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
            }
    }
}
return parts.join("&");
}

Now within the process function we could do something like this: 现在,在流程函数中,我们可以执行以下操作:

process(e) {
    var data = serialize(form);
    handlePostRequest(data, handleResponse); //initiates ajax request and passes in callback function
    e.preventDefault(); //prevents default behavior of loading new page with results;
}

Ok..whew. 好的。 We are almost done. 我们快完成了。

Here is the function that handles the ajax call: 这是处理ajax调用的函数:

function handlePostRequest(data, callback) {
    var xhr = createXHR(),
        data = data;

    xhr.open("POST", "login/processLogin.php");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            var status = xhr.status;
            if ((status >= 200 && status < 300)) || status === 304) {
                 callback(xhr.responseXML);
            } else {
              alert("An error occurred");
            }
        }
    };
    xhr.send(data);
}

Then the last and final piece would be the callback function. 然后,最后一块也是回调函数。

function handleResponse(response) {
    var xmlResponse = response,
        xmlDocumentElement = xmlResponse.documentElement,
        message = xmlDocumentElement.firstChild.data;

    document.getElementById("errorField").innerHTML = message;
}

It might seem overwhelming but it is a pattern that is followed for most post request. 它看起来似乎不堪重负,但这是大多数后期请求所遵循的模式。 In all honesty this is where the beauty of jQuery would come in. But it is always a good educational experience to see how it is done with plain JavaScript. 坦率地说,这就是jQuery的美所在。但是,看看纯JavaScript是如何实现的,这始终是一种很好的教育经验。 I'm sure I probably missed something, so if any questions let me know! 我确定我可能错过了一些东西,所以如果有任何问题让我知道! I'm going to sleep! 我要睡觉了!

我建议您使用jQuery,它的代码更少,并且更容易使用,这里是一个链接: http : //api.jquery.com/jQuery.ajax/

I recommend you use jQuery, instead of creating XmlHttpRequest objects manually, as it manages to solve some compatibility issues between browsers, and makes the whole thing way simpler. 我建议您使用jQuery,而不是手动创建XmlHttpRequest对象,因为它可以解决浏览器之间的一些兼容性问题,并使整个过程更简单。

With jQuery, you will be able to do the request using something like this: 使用jQuery,您将可以使用以下命令进行请求:

$.post({
    url: "http://example.com/....",
    data: {"username": "your_user_here", "password": "your_password_here"},
    success: function(){
        alert('Success!');
    }
});

Anyways, there are a lot of options there and the topic is quite long to fit in a SO answer, so I recommend you have a look at the jQuery Ajax documentation here: http://api.jquery.com/category/ajax/ 无论如何,那里有很多选择,而且这个主题很长才能适合SO答案,因此,我建议您在这里查看jQuery Ajax文档: http : //api.jquery.com/category/ajax/

and in particular this: http://api.jquery.com/jQuery.ajax/ 特别是: http : //api.jquery.com/jQuery.ajax/

Update 更新资料

The only problem here is that php usually expects to receive data in form-encoded format, but with this your script will get json data.. (so, expect not to be able to use $_POST ) with other languages (python, nodejs, ..) this is not a problem; 唯一的问题是php通常希望以表单编码的格式接收数据,但是与此同时,您的脚本将获得json数据。(因此,希望不能使用$_POST )与其他语言(python,nodejs, ..) 这不是问题; I don't know how to handle this with php but I'm pretty confident there's a way to do that. 我不知道如何用php处理这个问题,但我非常有信心做到这一点。 Of course, you can fallback on sending form-encoded data, but JSON is the de-facto standard for these things nowdays.. 当然,您可以回退发送经过表单编码的数据,但是如今,JSON是事实上的标准。

Sorry, I was remembering incorrectly, but the default behavior of jQuery is to urlencode the POST data, so you'll be fine with reading values from $_POST , when doing requests with the code above.. 抱歉,我记错了,但是jQuery的默认行为是对POST数据进行urlencode,因此使用上述代码进行请求时,最好从$_POST读取值。

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

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