简体   繁体   中英

Why does JavaScript alert display an empty string in Phonegap Android App while the code is working perfectly fine on browser?

I'm working on a simple PhoneGap application that communicates with a server that runs PHP, gets a string and displays it in JavaScript alert.

The App works perfectly fine on a browser. The JavaScript alert displays the string returned by the PHP code on the server. This action happens on click event of a button.

Here is the markup :

  <!DOCTYPE html>
<html xml:lang="en" lang="en">
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;">
        <title>PhoneGap</title>
        <script type="text/javascript" charset="utf-8" src="jquery.min.js"></script>
        <script src="cordova.js" charset="utf-8" type="text/javascript"></script>
        <script type="text/javascript" charset="utf-8" src="index.js"></script>
    </head>
    <body>
        <h1>Hello World!</h1>
        <button id="eventfire">Click</button>
    </body>
</html>

JS code

$(document).ready(function(){
    $("#eventfire").click(function(){
    var data = {
        "action": "test"
    }; 
    data=$.parseJSON('{ "name": "John" }');
     $.ajax({
            type: "POST",
            dataType: "text",
            url: "http://192.168.x.x/HelloWorldTest/response.php", //Relative or absolute path to response.php file
            data: data,
            success: function(data) {
            alert(data);
            alert("type is " + typeof data + ". Length is " + data.length);
            },
            error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.statusText);
        alert(xhr.responseText);
        alert(xhr.status);
        alert(thrownError);
    },
             statusCode: {
        400: function    () {
            alert("Bad request!");
        },
        401: function() {
            alert("Unauthorized!");
        },
        403: function() {
            alert("Forbidden!");
        },
        404: function() {
            alert("Page not found!");
        },                
        408: function() {
            alert("Request Timeout!");
        },
        200: function() {
            alert("page reached");
        },    
    }
        }); 
    });

})

PHP code

<?php
echo 'john';
?>

When I run this code on a AVD, the alert does not display the string. I have never seen such a alert getting displayed. The alert displayed inside the success function is shown below.

空字符串警报

On inspecting this string, I understood that the length is 0.

弦长

I was able to reproduce the same issue on browser with a string of 0 characters length.

I'm not sure why the piece of code that is working fine when run on browser but acts weirdly on AVD. The string was getting displayed as expected on browser but not on AVD.

Find below the screenshots of the same code displaying the correct alert on browser.

服务可用性在此处输入图片说明

I want to know the possible reasons of why the string from PHP is getting lost ?

I've never used PhoneGap but since your php file is stored on a different server than the files trying to call it, you will need to enable Cross-Origin Resource Sharing (CORS) (though I can't be sure this is the only issue)


Try adding Header set Access-Control-Allow-Origin "*" in your server's .htaccess file

By default, servers block access to resources like php files when the request comes from a file that is not stored on the same server.

For example, if I have a js file located at http://myfirstwebsite.com/awesome.js and in that file I make an ajax call to http://mysecondwebsite.com/loadstuff.php , the request will be blocked by the server and will produce the following error in the console:

XMLHttpRequest cannot load http://mysecondwebsite.com/loadstuff.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysecondwebsite.com' is therefore not allowed access.

I'm not sure if you can see this error in PhoneGap or where as I have never used it.

As the warning alludes to, in order to fix this, you must set the 'Access-Control-Allow-Origin' header to allow remote files to access the ones on your server.


Here is a tutorial explaining how to do that on Ubuntu

Just in case that link ever dies, here are the steps (copied right from that site)

  1. Make sure you have the mod_headers Apache module installed. to do this check out /etc/apache2/mods-enabled/ and see if there's a 'headers.load' in there. If there isn't then just sudo ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load

  2. Add the Access-Control-Allow-Origin header to all HTTP responses. You can do this by adding the line Header set Access-Control-Allow-Origin " " to the desired section in your configuration file (like the /etc/apache2/sites-available/default file). Saying " " will allow cross-site XHR requests from anywhere. You can say "www.myothersite.com" to only accept requests from that origin.

  3. Reload apache server. sudo /etc/init.d/apache2 reload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM