XMLHttpRequest - 空的responseText但状态200和readyState 4

时间:2014-04-14 19:17:41

标签: android cordova xmlhttprequest emulation cors

XMLHttpRequest - 清空responseText但状态200和readyState 4

我一直在尝试使用普通JS进行跨域请求。它在Firefox和Chromium中有效,但在Android Emulator中无效。

onload方法返回成功(status 200和readyState 4),但responseText为空。

window.addEventListener('load', function () {
    var xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open('GET', 'http://10.2.1.22/'); // My website running in local apache right now. It'll be in a webhosting.

    xmlHttpRequest.addEventListener('load', function () {
        document.body.appendChild(document.createTextNode(this.status + " - " + this.readyState)); // output: "200 - 4"
        document.body.appendChild(document.createTextNode(this.responseText)); // in browser output is a regular string ... in android emulator it's an empty string.
    });

    xmlHttpRequest.addEventListener('error', function (event) {
        document.body.appendChild(document.createTextNode("Error!")); // it's never called.
    });

    xmlHttpRequest.send();
});

我的网站发送以下标题:

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');

Cordova版本:

$ cordova --version
3.4.0-0.1.3

修改

APP_ROOT / config.xml中

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.xmlhttprequest" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>XMLHttpRequest</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

1 个答案:

答案 0 :(得分:0)

您是否将自己的网站添加到config.xml中的白名单?默认情况下,如果您未明确将白名单列入白名单,则列入白名单的所有文档都将返回空文档。这是设计的。您应该阅读有关白名单的信息:

http://docs.phonegap.com/en/3.4.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide