XMLHttpRequest POST无法正常工作?

时间:2014-07-02 07:30:28

标签: javascript android cordova xmlhttprequest

我正在尝试将一些数据发布到服务器,但它,返回状态0,它只是不能在android 4.2.2上工作,因为我正在使用cordova应用程序。跨域问题? 我还在header和config.xml中尝试了Access-Control-Allow-Origin = *。

var req = new XMLHttpRequest();

if (!method)
    method = "POST";

if (!contentType)
    contentType = "application/x-www-form-urlencoded";

req.open(method, url, true);

req.setRequestHeader("Content-type", contentType);
req.setRequestHeader("Accept", "application/json,text/javascript,");

var timeoutHandler = function() {
    //console.log("timeoutHandler: readyState: " + req.readyState);

    if (req.readyState >= 2)
        return;

    if (window.sus)
        window.sus.updateLimitedConn(true);

    if (err)
        err(1001);

    req.abort();
};

var reqTimeoutID = setTimeout(timeoutHandler, 30000);

req.onload = function() {
    //console.log("xhr onload: readyState: " + req.readyState + ", status: " + req.status);

    if (req.readyState != 4)
        return;

    clearTimeout(reqTimeoutID);

    if (req.status == 200) {
        if (window.sus)
            window.sus.updateLimitedConn(false);

        if (suc)
            suc(req.responseText);
    }
    else {
        if (window.sus && (req.status == 408 || (req.status >= 500 && req.status <= 599)))
            window.sus.updateLimitedConn(true);

        if (err)
            err(req.status);
    }
};

req.onerror = function() {
    //console.log("xhr onerror: readyState: " + req.readyState + ", status: " + req.status);
    clearTimeout(reqTimeoutID);
    if (err)
        err(1002);
};

req.send(data);

1 个答案:

答案 0 :(得分:0)

我想我遇到了类似的问题。试试这个:

在您的cordova config.xml 文件中添加:

<access origin="*" />

AndroidManifest.xml (platforms / android /)中添加:

<uses-permission android:name="android.permission.INTERNET" />
祝你好运!