php - Ajax PHP JavaScript : error when using POST method

标签 php javascript jquery ajax

我在 google 上搜索了一下,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');

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

谢谢

最佳答案

在调用 xhr.open 之后调用 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

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

关于php - Ajax PHP JavaScript : error when using POST method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182816/

相关文章:

javascript - 如果选中一个复选框,则禁用所有复选框,如果未选中,则启用

javascript - WordPress 插件如何处理表单提交

javascript - 当值相同时在选择上触发事件

javascript - 如何在需要 header 的axios发布请求中具有配置参数

jquery - 生成的 JsonResult 中的属性名称大小写不一致

javascript - 将类更改为另一个名称,这样它就不会在jquery中激活onClick,然后重置

php - Symfony2 用户提供者必须在登录时返回一个 UserInterface 对象

javascript - 使用 Ajax 和 Jquery 发送数据

php - 如何仅删除所有 anchor 标记和 href 属性?

javascript - 使用 jquery 在悬停时展开文本表单