繁体   English   中英

ajax php javascript:使用POST方法时出错

[英]ajax php javascript : error when using POST method

我在google上搜索过,关于stackoverflow的这个话题有很多问题。 例如“数据不是通过邮寄方法发送”等等。但似乎不是我的问题

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

Firefox(第21版):

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');

Chrome(第27版):

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数据?

谢谢

调用xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 在你打电话给xhr.open

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

暂无
暂无

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

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