phonegap jquery ajax失败($ .support.cors = true) [英] phonegap jquery ajax fails ($.support.cors = true)

查看:623
本文介绍了phonegap jquery ajax失败($ .support.cors = true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery.mobile-1.1.1
jquery-1.7.2.min
cordorva-1.9.0



I只是刚刚开始这个,并一直在旋转一个星期现在...我已经阅读每一篇文章,并尝试每一个组合,我可以想到,但仍然没有工作。作为最后一个手段,我把它从phonegap和一个真正的浏览器页面,我得到一些未定义的错误:

  /如果这些没有设置我得到NO Transport错误
$ .support.cors = true;
$ .mobile.allowCrossDomainPages = true;

//但是,使用上面定义的(true),以下是错误:
// xhr.statusText =error
// textStatus =error
// errorThrown.message =Access Denied


function login(username,password)
{
var serviceURL =http:// mobile.mydomain.com/;
var strData =username =+ username +& password =+ password;

//设置ajax调用的参数
var ajaxParams = {
type:'POST',
url:serviceURL +'mypage.php',
data:strData,
datatype:'json',
success:function(xmlData,textStatus,xhr){onLoginOK(xmlData,textStatus,xhr)},
error:function xhr,textStatus,errorThrown){
onLoginFailure(xhr,textStatus,errorThrown)},
timeout:5000,
cache:false
};

//使ajax调用
$ .ajax(ajaxParams);
}

函数onLoginOK(data,textStatus)
{
//可能不对,但是没有得到这么远!
var what = jQuery.parseJSON(data);

alert(登录结果:+数据);
if(what.status ==OK)
{
localStorage.setItem(door,what.username);
localStorage.setItem(knock,what.password);
localStorage.setItem(house,what.userid);
}
else if(what.status ==FAILED)
{
alert(Login failed:+ what.text);
}
}

函数onLoginFailure(xhr,textStatus,errorThrown)
{
alert(出现错误:服务器报告: xhr.responseText
+\\\
status:+ textStatus
+\\\
error:+ errorThrown);
}

在cordova.xml里面,我允许访问我的域:

 < access origin =http://mobile.mydomain.comsubdomains =true/>任何人都有建议吗?



=

==================================================== =====================
这是来自eclipse:

  07-27 09:12:16.612:I / dalvikvm(1295):找不到方法android.webkit.WebView。< init>,从方法org.apache.cordova.CordovaWebView引用。 
07-27 09:12:16.612:W / dalvikvm(1295):VFY:无法解析直接方法3116:Landroid / webkit / WebView;。< init& (Landroid / content / Context; Landroid / util / AttributeSet; IZ)V
07-27 09:12:17.339:I / webviewdatabase(1295):openOrCreateDatabase1
07-27 09:12:17.362: I / CordovaLog(1295):将日志级别更改为DEBUG(3)
07-27 09:12:17.362:I / CordovaLog(1295):找到的首选项useBrowserHistory = false
07-27 09: 12:17.378:E / dalvikvm(1295):无法找到类android.webkit.WebResourceResponse,从方法org.apache.cordova.CordovaWebViewClient.generateWebResourceResponse引用
07-27 09:12:17.378:W / dalvikvm(1295):VFY:无法解析Lorg / apache / cordova / CordovaWebViewClient中的新实例451(Landroid / webkit / WebResourceResponse;);
07-27 09:12:17.378:W / dalvikvm(1295):VFY:无法找到在签名中引用的类(Landroid / webkit / WebResourceResponse;)
07-27 09:12:17.386: W / dalvikvm(1295):VFY:无法找到在签名中引用的类(Landroid / webkit / WebResourceResponse;)
07-27 09:12:17.386:W / dalvikvm参考签名(Landroid / webkit / WebResourceResponse;)
07-27 09:12:17.386:I / dalvikvm(1295):无法找到方法android.webkit.WebViewClient.shouldInterceptRequest,从方法org.apache引用。 cordova.CordovaWebViewClient.shouldInterceptRequest
07-27 09:12:17.386:W / dalvikvm(1295):VFY:无法解决虚拟方法3127:Landroid / webkit / WebViewClient; .shouldInterceptRequest(Landroid / webkit / WebView; Ljava / lang / String;)Landroid / webkit / WebResourceResponse;
07-27 09:12:19.706:W / dalvikvm(1295):没有找到原生Lcom / carrieriq / iqagent / client / NativeClient的实现; .clientInit(Ljava / lang / Object;)I
07-27 09:12:21.979:I / Database(1295):sqlite返回:错误代码= 14,msg =无法在源行打开文件25467
07-27 09:12:22.198:I / (1295):错误:语法错误:意外令牌ILLEGAL at file:///android_asset/www/cordova-1.9.0.js:1012
07-27 09:12:22.347:I / Flex loadOperatorCode()strOp is AT& T
07-27 09:12:22.347:I / Flex(1295):loadOperatorCode()strMccList是
07-27 09:12:22.347:I / Flex 1295):loadOperatorCode()cr.query strMCC strMNC
07-27 09:12:22.354:I / Flex(1295):loadOperatorCode()mOperatorIndex ==> 1
07-27 09:12:24.167:I / Web控制台(1295):**错误**初始化网络连接:在文件:///android_asset/www/cordova-1.9.0找不到类。 js:5317
07-27 09:12:26.854:I / Web控制台(1295):** JSCallback错误:**请求失败。 at file:///android_asset/www/cordova-1.9.0.js:3747
07-27 09:12:28.331:I / Database(1295):sqlite返回:错误代码= 14,msg =打开文件在源线25467
07-27 09:12:28.347:I / Web控制台(1295):**错误:**语法错误:意外的令牌ILLEGAL在文件:/// android_asset / www / cordova- 1.9.0.js:1012
07-27 09:12:28.386:I / Web控制台(1295):**错误**初始化网络连接:在文件中找不到类:/// android_asset / www / cordova-1.9.0.js:5317


解决方案

在添加您的cordova或JQM脚本之前,您应该添加这些脚本。

 < script type =text / javascript> 
$(document).bind(mobileinit,function(){
$ .support.cors = true;
$ .mobile.allowCrossDomainPages = true;
});
< / script>

然后你应该像这样ajax请求

  $ 
.ajax({
cache:false,
type:'POST',// While GET working
async: false,
url:http://192.168.1.100/something.xml+?time =+ Date.now(),
data:{
key:value
},
dataType:xml,
success:function(xml){
},
error:function(xhr,ajaxOptions,thrownError){
alert(xhr.status);
alert(thrownError);
}
});

如果这不适用于你使用 XMLHttpRequest

  var req = new XMLHttpRequest 
req.open(POST,http://192.168.1.100/something.JPG,true);
req.setRequestHeader(Content-type,image / jpg);

req.onreadystatechange = function(){
if(req.readyState == 4){
if(req.status == 200){
var data = req.responseText;
}
}
};
req.send(null);


jquery.mobile-1.1.1 jquery-1.7.2.min cordorva-1.9.0

I'm just getting started with this and been screwing around with it for a week now... I've read every article out there and tried every combination I can think of but still nothing working. As a last resort I moved this out of phonegap and to a real browser page and I'm getting some undefined errors:

// if these are NOT set I get the "NO Transport" error
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;

// however, with the above defined (true), the following is the error:
// xhr.statusText = "error"
// textStatus = "error"
// errorThrown.message = "Access Denied"


function login(username, password)
{
  var serviceURL = "http://mobile.mydomain.com/";
  var strData = "username="+username +"&password="+password;

  // setup the paramaters for the ajax call
  var ajaxParams = {  
      type: 'POST',
      url: serviceURL + 'mypage.php',
      data: strData,
      datatype: 'json',
      success: function(xmlData, textStatus, xhr) { onLoginOK(xmlData, textStatus, xhr) },
      error: function(xhr, textStatus, errorThrown) { 
                      onLoginFailure(xhr, textStatus, errorThrown) },
      timeout: 5000,
      cache: false
  };

  // make the ajax call
  $.ajax(ajaxParams);
}

function onLoginOK(data, textStatus)
{
  // probably not right but haven't gotten this far!
  var what = jQuery.parseJSON(data); 

  alert("Login results: " + data); 
  if(what.status == "OK")
  {
    localStorage.setItem("door", what.username);
    localStorage.setItem("knock", what.password);
    localStorage.setItem("house", what.userid);
  }
  else if(what.status == "FAILED")
  {
      alert("Login failed: " +what.text);
  }
}

function onLoginFailure(xhr, textStatus, errorThrown)
{
  alert("There was an error: The server reported: " + xhr.responseText 
        +"\nstatus: " +textStatus 
        + "\nerror: " +errorThrown);
}

Inside the cordova.xml I allowed access to my domain with:

<access origin="http://mobile.mydomain.com" subdomains="true "/> 

Anyone have any suggestions?

======================================================================== this is from eclipse:

07-27 09:12:16.612: I/dalvikvm(1295): Could not find method android.webkit.WebView.<init>, referenced from method org.apache.cordova.CordovaWebView.<init>
07-27 09:12:16.612: W/dalvikvm(1295): VFY: unable to resolve direct method 3116: Landroid/webkit/WebView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;IZ)V
07-27 09:12:17.339: I/webviewdatabase(1295): openOrCreateDatabase1
07-27 09:12:17.362: I/CordovaLog(1295): Changing log level to DEBUG(3)
07-27 09:12:17.362: I/CordovaLog(1295): Found preference for useBrowserHistory=false
07-27 09:12:17.378: E/dalvikvm(1295): Could not find class 'android.webkit.WebResourceResponse', referenced from method org.apache.cordova.CordovaWebViewClient.generateWebResourceResponse
07-27 09:12:17.378: W/dalvikvm(1295): VFY: unable to resolve new-instance 451 (Landroid/webkit/WebResourceResponse;) in Lorg/apache/cordova/CordovaWebViewClient;
07-27 09:12:17.378: W/dalvikvm(1295): VFY: unable to find class referenced in signature (Landroid/webkit/WebResourceResponse;)
07-27 09:12:17.386: W/dalvikvm(1295): VFY: unable to find class referenced in signature (Landroid/webkit/WebResourceResponse;)
07-27 09:12:17.386: W/dalvikvm(1295): VFY: unable to find class referenced in signature (Landroid/webkit/WebResourceResponse;)
07-27 09:12:17.386: I/dalvikvm(1295): Could not find method android.webkit.WebViewClient.shouldInterceptRequest, referenced from method org.apache.cordova.CordovaWebViewClient.shouldInterceptRequest
07-27 09:12:17.386: W/dalvikvm(1295): VFY: unable to resolve virtual method 3127: Landroid/webkit/WebViewClient;.shouldInterceptRequest (Landroid/webkit/WebView;Ljava/lang/String;)Landroid/webkit/WebResourceResponse;
07-27 09:12:19.706: W/dalvikvm(1295): No implementation found for native Lcom/carrieriq/iqagent/client/NativeClient;.clientInit (Ljava/lang/Object;)I
07-27 09:12:21.979: I/Database(1295): sqlite returned: error code = 14, msg = cannot open file at source line 25467
07-27 09:12:22.198: I/Web Console(1295): Error: SyntaxError: Unexpected token ILLEGAL at file:///android_asset/www/cordova-1.9.0.js:1012
07-27 09:12:22.347: I/Flex(1295): loadOperatorCode() strOp is AT&T
07-27 09:12:22.347: I/Flex(1295): loadOperatorCode() strMccList is 
07-27 09:12:22.347: I/Flex(1295): loadOperatorCode() cr.query strMCC strMNC 
07-27 09:12:22.354: I/Flex(1295): loadOperatorCode() mOperatorIndex ==> 1
07-27 09:12:24.167: I/Web Console(1295): **Error** initializing Network Connection: Class not found at file:///android_asset/www/cordova-1.9.0.js:5317
07-27 09:12:26.854: I/Web Console(1295): **JSCallback Error:** Request failed. at file:///android_asset/www/cordova-1.9.0.js:3747
07-27 09:12:28.331: I/Database(1295): sqlite returned: error code = 14, msg = cannot open file at source line 25467
07-27 09:12:28.347: I/Web Console(1295): **Error:** SyntaxError: Unexpected token ILLEGAL at file:///android_asset/www/cordova-1.9.0.js:1012
07-27 09:12:28.386: I/Web Console(1295): **Error** initializing Network Connection: Class not found at file:///android_asset/www/cordova-1.9.0.js:5317

解决方案

First of all you should add these before adding your cordova or JQM scripts

<script type="text/javascript">
$(document).bind("mobileinit", function() {
    $.support.cors = true;
    $.mobile.allowCrossDomainPages = true;
});
</script>

Then you should make a ajax request like this

$
.ajax({
    cache : false,
    type : 'POST',//While GET working
    async: false,
    url : "http://192.168.1.100/something.xml" + "?time=" + Date.now(),
    data : {
        key : "value"
        },
    dataType : "xml",
    success : function(xml) {
            },
    error : function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

If this doesn't works for you that make use of XMLHttpRequest

var req = new XMLHttpRequest();
req.open("POST", "http://192.168.1.100/something.JPG", true);
req.setRequestHeader("Content-type", "image/jpg");

req.onreadystatechange = function() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var data = req.responseText;
        }
    }
};
req.send(null);

这篇关于phonegap jquery ajax失败($ .support.cors = true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆