0
votes

I have a simple index.html file to display a string from test.txt file using the .load function from jquery library and put the string content to html (div class="konten").

This the following HTML script :

<script type="text/javascript" charset="utf-8" src="js/lib/cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="js/lib/jquery-2.0.2.js"></script>
...
<body onload="init();">
    <div class="center">
        <div class="konten"></div>
    </div>
</body>
...

and the js :

$(document).ready(function(){
    $('.konten').load('test.txt',function(responseTxt,statusTxt,xhr){
      if(statusTxt=="success")
        alert("External content loaded successfully!");
      if(statusTxt=="error")
        alert("Error: "+xhr.status+": "+xhr.statusText);
    });
});

when I try to run the index.html file on the desktop browser (quick test), there is not displaying the content of test.txt, and showing the javascript alert Error: 404: error.

Is there anything wrong with the script that I wrote?

HTML editor : Eclipse 4.2.2 (Juno)

cordova-1.9.0

jquery-2.0.2

2

2 Answers

0
votes

Try your code inside the deviceready event instead of document ready event.

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
   $('.konten').load('test.txt',function(responseTxt,statusTxt,xhr){
     if(statusTxt=="success")
        alert("External content loaded successfully!");
     if(statusTxt=="error")
        alert("Error: "+xhr.status+": "+xhr.statusText);
    });
}
0
votes

You can use the below login. By this way, you can invoke the required function based on whether you are using a desktop browser or in a mobile app.

function onBodyLoad() {
    // these are useful later in the app, might as well set early
    window.isRipple = (window.tinyHippos != null);
    window.isPhoneGap = /^file:\/{3}[^\/]/i.test(window.location.href);
    window.isIOS = !window.isRipple && navigator.userAgent.match(/(ios|iphone|ipod|ipad)/gi) != null;
    window.isAndroid = !window.isRipple && navigator.userAgent.match(/(android)/gi) != null;

    // stuff I use for debugging in chrome
    if (window.isPhoneGap) {
       document.addEventListener("deviceready", onDeviceReady, false);
    } else {
       onDeviceReady();
    }
}

You can call this function on body load event of the page.

<body onload="onBodyLoad()"> 

I remember seeing this logic posted by someone else in SO. The real credit should go to that user.