【问题标题】:XMLHttpRequest - empty responseText but status 200 and readyState 4XMLHttpRequest - 空 responseText 但状态 200 和 readyState 4
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2018-11-11
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多