【问题标题】:Cordova application XmlHttpRequestCordova 应用程序 XmlHttpRequest
【发布时间】:2017-05-20 02:46:59
【问题描述】:

我正在尝试从我的 cordova 应用程序发出 POST http 请求,但它不工作(ios 或 android),我一直收到 httpRequest.status 等于 0 并且 httpRequest.responseText 为空,并且未到达服务器.

有很多关于这方面的信息,但我无法让它发挥作用。我的 config.xml 配置如下:

<access origin="*">

我也尝试对 google 或其他已知服务器进行 GET 查询,但也无法正常工作。

这是我正在使用的代码。

function alertContents(httpRequest)
{
  if (httpRequest.readyState == 4)
  {
    // Everything is good, the response is received
    if ((httpRequest.status == 200) || (httpRequest.status == 0))
    {
      alert("The response was: "  + httpRequest.status + " - " +  httpRequest.responseText);
    } else {
      alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
    }
  }
}

function send_with_ajax() {
alert("Pushing data");

  var the_url = 'http://<servier ip>:<port>/service';
  var httpRequest = new XMLHttpRequest();

  httpRequest.onreadystatechange = function() { alertContents(httpRequest); };

  httpRequest.open("POST", the_url, true);

  httpRequest.send(null);

}

根据网上的信息,它应该可以工作,有人知道我是否遗漏了什么吗?,

非常感谢。

【问题讨论】:

  • send_with_ajax 怎么叫?
  • 一旦收到这样的事件“deviceready”就会调用它: var buttonElement = document.getElementById('data_button'); buttonElement.addEventListener("click", send_with_ajax, false);
  • 你的问题。你没有取消点击事件...

标签: javascript android iphone cordova


【解决方案1】:

单击提交按钮或链接将导致页面提交/导航离开。所以你需要取消点击事件,这样动作就不会发生。

function send_with_ajax(evt) {
    evt.preventDefault();
    ...

【讨论】:

    【解决方案2】:

    您可能需要使用此处指定的内容安全策略将要请求的域列入白名单:http://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/

    为了解决这个问题,我不得不添加一个类似于这个的元标记:

    <!-- This policy allows everything (eg CSS, AJAX, object, frame, media, etc) except that 
    * CSS only from the same origin and inline styles,
    * scripts only from the same origin and inline styles, and eval()
    -->
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
    

    并从我的服务器返回 Access-Control-Allow-Origin: * 标头。

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      相关资源
      最近更新 更多