PhoneGap ajax call fails everytime

后端 未结 6 1931
臣服心动
臣服心动 2021-01-15 12:27

I am developing a mobile application using PhoneGap, and I have to access some services from another project. I am using jquery-2.0

6条回答
  •  鱼传尺愫
    2021-01-15 13:12

    The problem is that your phonegap application is requesting a local file from something that isn't a webserver. The local file is delivered with NO HTTP HEADERS - that means no "200 OK" header and no "404 Not Found" errors. So, the status code is assumed to be 0.

    Straight javascript XHR will need to ignore status and perform your action on readystate == 4 (finished and ready). Like this:

        var myrequest = new XMLHttpRequest();
        myrequest.open('GET','localfile.html');
        myrequest.onreadystatechange = function(){
            if(myrequest.readyState == 4) {
                var result = myrequest.responseText;
            }
        }
        myrequest.send();
    

    In MooTools, it's a relatively straightforward task of implementing an altered status test in the Request class - altering the return code test to also accept 0 for true. Like this:

    Request.implement({
        isSuccess: function(){
            var status = this.status;
            return ((status >= 200 && status < 300) || status === 0);
        }
    });
    

    jQuery.... I have some things I'd like to say about jQuery - but I'll hold my tongue because this seems like a classy place.

    To prepare jQuery for status == 0, you need to use the always event instead of the success event, you can test the status code there.

    $.ajax({
       url: '/echo/html/',
       type: 'PUT',
       data: "email=a@b.com"
     }).always(function(data, textStatus, jqXHR){
       switch(textStatus) {
         case 200:
             case 0:
             alert('Success.');
                 break;
             case 404:
                 alert('oops');
                 break;
       }
     });
    

    Ajax in Cordova/Phonegap - Yay!

提交回复
热议问题