5

我在谷歌上搜索,关于这个话题在stackoverflow上有很多问题。例如“数据未通过 post 方法发送”等。但似乎没有回答我的问题

情况与其他问题几乎相同。这些是错误消息:

火狐(v21):

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

铬(v27):

Uncaught Error: InvalidStateError: DOM Exception 11

当请求由 发送时GET,没有错误。并且所有 GET 数据都接收良好。

但是当通过POST+发送时setRequestHeader, itu 会出现上述错误。删除后setRequestHeader,错误消失了。没有错误,但没有收到 POST 数据。我print_r($_POST); 那么数组是空的

问题已更新。这是调用者:

goServer({
    url     : 'users/sign-in.php',
    method  : 'POST',
    data    : 'randomId=' + randomId + '&name=' + name + '&password=' + password,
    done    : function(response) {
        alert(response);
    },
    fail    : function(response) {
        alert(response);
    }
});

这是功能(对不起,长线):

function randomString() {
    var str = new Date().getTime(),
    str2    = Math.random();

    str     = str.toString();
    str2    = str2.toString();
    str2    = str2.substring(2,7);
    str     += str2;

    return str;
}



function goServer(opts) {
    var xhr    = new XMLHttpRequest();
    xhr.onreadystatechange = requestComplete;

    function requestComplete() {
        if ( xhr.readyState === 4 ) {
            if ( xhr.status === 200 ) {
                opts.done(xhr.responseText);
            } else {
                opts.fail(xhr.responseText);
            }
        }
    }

    if ( !opts.method || opts.method === undefined ) {
        opts.method    = "GET";
    }

    if ( !opts.cache || opts.cache === undefined ) {
        opts.cache    = false;
    }

    if ( opts.cache === false ) {
        opts.url    += '?nocache=' + randomString();
    } else {
        opts.url    += '?nocache=false';
    }

    if ( opts.method === "GET" ) {
        if ( opts.data !== '' && opts.data !== undefined ) {
            opts.url    += '&' + opts.data;
        }
        opts.data    = '';
    } else {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }

    xhr.open(opts.method, opts.url, true);
    xhr.send(opts.data);

}

注意,数据参数(opts.data)在GET发送时设置为url。当通过 POST 发送时,参数设置为 xhr.send(opts.data);

问题:如何正确获取 POST 数据?

谢谢

4

1 回答 1

12

打电话xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');后打电话xhr.open

opts.data应该是一个包含键/值对的字符串。例如key=value&method=post

于 2013-06-19T04:35:13.317 回答