简体   繁体   中英

connecting android phonegap app to localhost in emulator

hope u guys will be able to help me. I'm relatively very new to phonegap. I've cracking my head on this for a week+ now on this subject. I have a dbase wcf rest service in C# and have built an android client to call this service. Everything seem to be working fine when I test this app in wp7 ie call this service in json format. but when I migrated this app to eclipse android environment and configured relevant settings the app will not run successfully even after I changed the url: http//:localhost:1067/Service1 to http//:10.0.2.2:1067/Service1. I'm still using a demo app which I have modified to the following

index.html

<!doctype html>
<html>
<head>
    <meta name="viewport" content="width=320 user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>PhoneGap WP7</title>
    <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8" />
    <script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="console.js"></script>
    <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="init.js"></script>

</head>
<body>
  <div>
    <h1 id="welcomeMsg">Welcome</h1>
    <p><a href="#" onclick="login(); return false;">log in</a></p>
    <p><a href="#" onclick="getAjax(); return false;">Get Ajax</a></p>
    <p><a href="#" onclick="postAjax(); return false;">Post Ajax</a></p>
    <p><a href="#" onclick="getSingle(); return false;">Get Single Item</a></p>
    <p><a href="#" onclick="deleteSingle(); return false;">Delete</a></p>
    <p><a href="#" onclick="updateSingle(); return false;">Update</a></p>
    <p><a href="#" onclick="identify(); return false;">Identify</a></p>
    <p><a href="#" onclick="logViaForm(); return false;">Log via Form</a></p>
    <p><a href="#" onclick="logout(); return false;">log out</a></p>

    <p id="errorMessage" class="err"></p>
    <p id="loginCall"></p>
    <p id="ajaxCall"></p>
    <p id="postAjaxCall"></p>
    <p id="getSingleCall"></p>
    <p id="deleteSingleCall"></p>
    <p id="updateSingleCall"></p>
    <p id="identifyCall"></p>
    <p id="logViaFormCall"></p>
    <p id="logoutCall"></p>
    <input type="text" id="myTest" value="1" name="myTest" />
    </div>
   </body>
</html>

and the init.js

$(document).ready(function () {
    document.addEventListener("deviceready", onDeviceReady, false);
    jQuery.support.cors = true; //Cross-Origin Resource Sharing
});

// phonegap is initialised
function onDeviceReady() {
    $("#welcomeMsg").append("...Ready");
}

function showAlert(msg) {
    navigator.notification.alert(
                    msg, // message
                    alertDismissed, // callback
                    'Alert', // title
                    'Done'  // buttonName
                    );
}

function showError(error, otherInfo) {
    var element = document.getElementById('errorMessage');
    element.innerHTML = "Errors: " + error.Message + "<br>" + (otherInfo ? otherInfo : "");
}

function getAjax() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'GET',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Idi":5, "Type": "mike" }'
    })
    .done(function (data) {
        var element = document.getElementById('ajaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) {
         showError(error);
     })
     .always(function () { showAlert("complete"); });
 }


function postAjax(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Id":5, "StringValue": "jerry 22" }'
    })
    .done(function (data) {
        var element = document.getElementById('postAjaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function login() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Username":"test", "Password": "test" }'
    })
    .done(function (data) {
        var element = document.getElementById('loginCall');
        element.innerHTML = "Login Succesfull ? " + data;
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function logout() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/logout',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('logoutCall');
        element.innerHTML = "Login Out Succesfull ? " + data;
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function getSingle() {
    var longcentre = "3.355";
    var latcentre = "6.602";
    var locname = "hotel";
    var searchrad = "10";


    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/?lat1='+latcentre+'&long1='+longcentre+'&srad='+searchrad+'&lname='+locname+'',
        //   url: 'http://10.0.2.2/estatewcf/Service1/?lat1=6.602&long1=3.355&srad=2.5&lname=bank',
        type: 'GET',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('getSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}



function deleteSingle(parameters) {

    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/88',
        type: 'DELETE',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
    .done(function (data) {
        var element = document.getElementById('deleteSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function updateSingle(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/99',
        type: 'PUT',
        //headers:
        beforeSend: function (xhr) {
            //xhr.overrideMimeType('text/plain; charset=x-user-defined');
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "Id":99, "StringValue": "JERRY 22 " }'
    })
    .done(function (data) {
        var element = document.getElementById('updateSingleCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
    .fail(function (xhr, status, error) { showError(error); })
    .always(function () { showAlert("complete"); });
}

function identify(parameters) {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login/identify',
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    })
     .done(function (data) {
         var element = document.getElementById('identifyCall');
         element.innerHTML = JSON.stringify(data, null, "\t");
     })
      .fail(function (xhr, status, error) { showError(error); })
      .always(function () { showAlert("complete"); });
}

function postAjax1(parameters) {

    var id = "2";
    var mysearchradius = "ope";

    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/Service1/',
        type: 'POST',
        //headers:
        //beforeSend: function (xhr) {
        //},
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: '{ "IDn":"' + id + '","type1":"' + mysearchradius + '" }'
    })
    .done(function (data) {
        var element = document.getElementById('postAjaxCall');
        element.innerHTML = JSON.stringify(data, null, "\t");
    })
     .fail(function (xhr, status, error) { showError(error); })
     .always(function () { showAlert("complete"); });
}

function logViaForm() {
    var jqxhr = $.ajax({
        url: 'http://10.0.2.2/estatewcf/login.aspx',
        type: 'GET',
        dataType: 'html'
    })
                .done(function (data) {
                    var eventVal = $(data).find('#__EVENTVALIDATION').attr('value');
                    var viewState = $(data).find('#__VIEWSTATE').attr('value');
                    //build post data
                    var postData = { __VIEWSTATE: viewState, __EVENTVALIDATION: eventVal, UserName: "test1", Password: "test2", LoginButton: "Log In" };

                    var jqxhr1 = $.ajax({
                        url: 'http://10.0.2.2/estatewcf/login.aspx',
                        type: 'POST',
                        dataType: 'html',
                        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                        data: postData
                    })
                    .done(function (data, status, jqxhr1) {
                        //this works but we will get an error dues to the redirect to the home.aspx
                        //TODO: need to handle that
                        var element = document.getElementById('logViaFormCall');
                        element.innerHTML = "Login Succesfull ! " + jqxhr1.status;
                    })
                     .fail(function (xhr, status, error) {
                         showError(error, "TODO: Works but need to handle redirect!!");

                         //but it really works!
                         var element = document.getElementById('logViaFormCall');
                         element.innerHTML = "Login Succesfull ! Verify that Authenticated AJAX calls work!";
                     })
                     .always(function () { showAlert("complete login"); });
                })
                .fail(function (xhr, status, error) { showError(error); })
                .always(function () { showAlert("complete"); });
}

cordova.xml

<cordova>
    <!--  
    access elements control the Android whitelist.  
    Domains are assumed blocked unless set otherwise
     -->

    <access origin="http://127.0.0.1*"/> <!-- allow local pages -->

    <!-- <access origin="https://maps.googleapis.com/maps/api/js?key=AIzaSyDD353fOPh-KBUQ-2ekPCg75uxXRn0D9Tk&sensor=false" /> allow any secure requests to example.com -->
    <!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www -->
    <!-- <access origin="*."/> Allow all domains, suggested development use only -->

    <log level="DEBUG"/>
    <preference name="classicRender" value="true" />
</cordova

as I have said earlier I have tested the wcf service locally withing vs2010 server and iis7 It seems to be working well, but Im not able to get it to work in android. Any help will be appreciated. Thanks in advance.

I found out that there is notting wrong with this code other than to un-comment the commented whitelist part ie converting :

<!-- <access origin="https://10.0.2.2*" subdomains="true" /> such as above, but including subdomains, such as www --> to

<access origin="https://10.0.2.2*" subdomains="true" />

and that solved it.

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