【发布时间】:2014-05-28 21:43:26
【问题描述】:
XMLHttpRequest - 空 responseText 但状态为 200 和 readyState 4
我一直在尝试使用纯 JS 进行跨域请求。它在 Firefox 和 Chromium 中有效,但在 Android 模拟器中无效。
onload 方法返回成功(状态 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 --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>
【问题讨论】:
标签: android cordova xmlhttprequest emulation cors