How to make a connection to PHP file on a Webserver using PhoneGap(Android app) in real time?

独自空忆成欢 提交于 2019-12-10 17:45:08

问题


The below given code works fine using a wamp server on localhost.It is calling a php file that connects to the MySql DB and returns data.

However i am trying to build a mobileapp using PhoneGap. The below code is in a HTML file. My questions is how will my html file make a connection with the server using ajax once I upload it to phonegap and generate the .apk file. Since the below code just calls the getbustime.php file without any web server parameters.

i have devloped my app in phonegap using HTML,jQueryMobile,Ajax and now willing to upload help ?

  function getBusTime(){



                         if (window.XMLHttpRequest)
                        {// code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp=new XMLHttpRequest();
                        }
                      else
                        {// code for IE6, IE5
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                        }
                      xmlhttp.onreadystatechange=function()
                        {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200)
                          {

                         document.getElementById("resultLogBus").innerHTML=xmlhttp.responseText;

                    // $('#resultLogBus').html(xmlhttp.responseText).selectmenu( "refresh");
                         }
                        }

                      xmlhttp.open("GET","getbustime.php?direction="+direction+"&busnum="+busnum+"&dayofweek="+dayofweek+"&stopname="+stopname+"&starttime="+starttime+"&endtime="+endtime,true);
                      xmlhttp.send();



    }//End of function getBusTime


</script>

回答1:


Basically, you need to set a full path to the server/php file in your ajax call like so:

xmlhttp.open("GET","http://<YOUR_SERVER_NAME>/getbustime.php?direction="+direction+"&busnum="+busnum+"&dayofweek="+dayofweek+"&stopname="+stopname+"&starttime="+starttime+"&endtime="+endtime,true);


A couple other things you may ALSO need to do depending on your circumstances are:

  1. set this tag in the phonegap config.xml:

    <access origin="*" />

  2. I do all my phonegap development in Chrome and it enforces Cross-Origin security. Once you try to test against your server's real address (instead of localhost) Chrome will block it unless the server is set up for CORS. Easy way to enable this for testing in PHP on your server is:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type');



来源:https://stackoverflow.com/questions/22124308/how-to-make-a-connection-to-php-file-on-a-webserver-using-phonegapandroid-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!