Cordova для Android - не работает javascript и jquery - PullRequest
0 голосов
/ 11 января 2019

Javascript / Ajax / Jquery - ни один из них не работает в моем приложении Cordova (PhoneGap) для Android. Все, что он показывает, это htmlheader с его метками, но таблица не заполнена jsondata от внешнего URL. Я протестировал его в браузере, и он отлично работает. Но пока не для Android.

В чем может быть проблема?

index.html

<!DOCTYPE html>

<html>
<head>

    <meta http-equiv="Content-Security-Policy" content="default-src *;">
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="getLivsmedelsData.js"></script>

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

    <title>Hello World</title>
</head>
<body>

    <div class="container">

      <div class="livsmedelsmall">
          <h1>Sökning av livsmedel</h1>

          <form class="form">
              <div class="form-group">
                  <label for="livsmedelsSokOrd">Livsmedel</label>
                  <input type="search" class="form-control" id="livsmedelsSokOrd" placeholder="t ex makaroner">
              </div>
              <button type="button" class="btn btn-default" id="sok-button">Sök</button>
          </form>
          <table id="tabell" class="table">
              <thead>
              <tr>
                  <th>Livsmedel</th>
                  <th>Energi (kcal/100g)</th>
                  <th>Kolhydrater</th>
                  <th>Protein</th>
                  <th>Fett</th>
              </tr>
              </thead>
              <tbody>

              </tbody>
          </table>
      </div>
  </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>


</body>

getLivsmedelsData.js

var dataList = {

isInLocalStorage: false,

init: function() {

    this.bindEvents();


},

bindEvents: function() {

    this.updateLocalStorage();

    var me = this;
    var parseCheck = setInterval(function() {
        if(this.isInLocalStorage){
            me.parseJSONdata();
            clearInterval(parseCheck);
        }
    }, 500);




},

parseJSONdata: function() {

    var rawJSONdata = window.localStorage.getItem("key");

    console.log('retrievedObject: ', JSON.parse(rawJSONdata));

    var jSONdata =  JSON.parse(rawJSONdata);

    jSONdata.forEach(function (item) {
    var newCells = new Array(5);
    var table = $('#tabell');
    var newRow = table.get(0).insertRow(-1);
    for (var k = 0; k < newCells.length; k++) {

        newCells[k] = newRow.insertCell(k);
    }
    newCells[0].innerHTML = item.namn;
    newCells[1].innerHTML = item.energi;
    newCells[2].innerHTML = item.kolhydrater;
    newCells[3].innerHTML = item.protein;
    newCells[4].innerHTML = item.fett;
    });


},

updateLocalStorage: function() {

    var targetVal = "pizza";

    var url1 = "https://webservice.informatik.umu.se/webservice_livsmedel/getlivsmedel.php";
    var url2 = url1.concat("?namn=");
    var url3 = url2.concat(targetVal);
    var theUrl = url3.concat("&callback=getLivsmedel");

    getJSONdata(this.result, targetVal, theUrl);


},

result: function(jsonData) {

    window.localStorage.setItem("key", JSON.stringify(jsonData));

    this.isInLocalStorage = true;

}


}



window.onload = function() {

dataList.init();

}


function getJSONdata(callback, target, theUrl) {

//Om det finns ett innehåll (dvs längden är större än 0)
if (target.length > 0) {

    //Utför en förfrågan till webbtjänsten
    $.ajax({
        url: theUrl,
        dataType: "jsonp",
        data: {
            limit: 15,
            name: target
        },
        // Om förfrågan gått bra...
        success: function (response) {

            var foodArray = response.livsmedel;
                            callback(foodArray);

        }, error: function(xhr, status, error) {

                        var err = eval("(" + xhr.responseText + ")");
                        console.log(err);

                    }
    });
}
}

config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.jsonajax.food" version="1.0.0" xmlns="http://www.w3.org /ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<feature name="Whitelist">
    <param name="android-package"  value="org.apache.cordova.whitelist.WhitelistPlugin" />
    <param name="onload" value="true" />
</feature>
<name>FoodData</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="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<allow-intent href="market:*" />
<preference name="loglevel" value="DEBUG" />

1 Ответ

0 голосов
/ 11 января 2019

window.onload? только для браузера!

Где ваша функция ondeviceready () для приложения cordova? следует поместить init () внутри функции ondeviceready ()

...