【问题标题】:phonegap javascript html get requestsphonegap javascript html 获取请求
【发布时间】:2018-01-20 08:23:08
【问题描述】:

我正在尝试从 phone-gap 应用程序向我的网站发出 http 获取请求。以下代码在我使用 chrome 的笔记本电脑上运行良好,但一旦转换为应用程序,它就不再工作了。特别是,phonegap 可以很好地编译代码并给我一个完美的 .apk 文件,但只有文本“qwer”被放到屏幕上。代码如下:

<p id="output"></p>

<script>

    var theUrl = "https://example.com"

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            document.getElementById("output").innerHTML = xmlHttp.responseText + "qwer"
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);


</script>

请注意,当您执行获取请求时,我的网站当前返回“asdf”

我在 chrome 中运行它时得到的输出是这样的:

asdf qwer

但是当它作为一个 android 应用程序运行时,我得到了这个:

qwer

另外我想提一下,我已经阅读了所有这些内容,但没有一个特别有用:

run https request in phone gap
https request doesn't work in phonegap-iphone app Want to use https request in phonegap application on iphone

当请求来自应用程序时,get 请求似乎返回一个空字符串,因为没有引发错误并且它允许我将字符串添加在一起。

我想知道如何解决这个问题,以便在应用程序表单中工作。我怀疑有某种内置的 phonegap 功能可以做这种事情。

谢谢

编辑:

我已经在服务器端处理了 CORS。我在heroku上使用python。这是我的代码:

#!/usr/bin/env python
import gevent.monkey
gevent.monkey.patch_all()
import bottle
import os
@bottle.route('/')

def index():
    bottle.response.set_header("Content-Type", "text/turtle")
    bottle.response.set_header("Content-Location", "mydata.ttl")
    bottle.response.set_header("Access-Control-Allow-Origin", "*")
    return("asdf")

bottle.run(server='gevent', host='0.0.0.0', port=os.environ.get('PORT', 5000))

如果我需要做其他事情来修复它,请告诉我

【问题讨论】:

  • 您是否在链接中输入了正确的参数?顺便说一句,最好将xmlhttp.readyState 更改为this.readyState 并将xmlhttp.status 更改为this.status,因为您已经在当前上下文中创建了实例。
  • 你试过不使用 https 吗?你在 5000 端口上运行 https 吗?

标签: javascript phonegap


【解决方案1】:

我不确定是什么问题,但我认为这可能与 CORS(跨域资源共享)有关。

你必须设置 访问控制允许来源

您的浏览器正在发出请求并且工作正常,但是在移动设备上您必须设置一些额外的参数

https://www.telerik.com/blogs/using-existing-backend-services-in-phonegap-cordova-applications

这个链接可能有用,可能不是 java 的东西,而是 Access-Control-Allow-Origin 的设置。看看吧。

【讨论】:

    【解决方案2】:

    检查您的 config.xml 是否确实在导入 whitelist-plugin 并允许 http 和 https URL。

    <!-- Allow links to web pages to open in a browser -->
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多