PhoneGap(Cordova.js)和JQuery.Ajax没有合作
我使用Phonegap + Jquery定位Andriod 4.12构建了一个html页面。
我的业务要求是使用cordova.js的相机API拍照,然后将拍摄的照片发布到ASMX网络服务。
问题:当我添加对Cordova.js的引用并运行应用程序时,我在LogCat中收到错误“Uncaught ReferenceError:$ is not defined”但是如果我删除对cordova.js的引用一切正常并且我能够发布数据到Web服务。
我附上我的代码供参考。
Capture Photo var varType; var varUrl; var varData; var varContentType; var varDataType; var varProcessData; function InsertDetails() { alert('Inserting Details'); varType = "POST"; varUrl = "http://mobile.comp.com/service/userservice.asmx/InsertDetails"; varContentType = "application/json; charset=utf-8"; varDataType = "json"; varProcessData = true; var uname = document.getElementById('txtname'); var pwd = document.getElementById('txtpwd'); CallService(uname.value, pwd.value); return true; } //Generic function to call AXMX/WCF Service function CallService(u, p) { $.ajax({ type: varType, url: varUrl, data: '{"username":"' + u + '","password":"' + p + '"}', contentType: varContentType, dataType: varDataType, processdata: varProcessData, success: function (msg) { ServiceSucceeded(msg); }, error: ServiceFailed }); } function ServiceSucceeded(result) { var myObject = eval('(' + result.d + ')'); alert(myObject); } function ServiceFailed(result) { alert('Service call failed: ' + result.status + '' + result.statusText); varType = null; varUrl = null; varData = null; varContentType = null; varDataType = null; varProcessData = null; }
请帮我解决这个问题。
对类似问题进行一些搜索会显示一些可能的答案。
1)在本地而不是从CDN加载jQuery。 你似乎已经这样做但我会为其他有类似问题的人提到它。
在Android 3.2上找不到jQuery的华硕平板电脑上的$
2)告诉jQuery允许跨域请求。 请查看以下链接中的“$ .support.cors”和“$ .mobile.allowCrossDomainPages”部分。
https://demos.jquerymobile.com/1.2.0/docs/pages/phonegap.html
3)告诉jQuery好玩。 可能是cordova.js正在使用另一个想要使用$的JS库。 因为你首先加载cordova,所以另一个JS库在jQuery之前声明了$。
谢谢尼克的帮助。 第三个链接有帮助
最后我的代码工作了
我添加了以下代码行,它为我带来了魔力。
jQuery.noConflict();
之后JQuery得到了认可。 确保遵循javascripts的正确顺序,否则代码将无法正常工作。
我引用js文件的顺序:
- 引用JQuery.js(本地添加到项目中)
- jQuery.noConflict();
- 服务电话的Javascript代码
- 参考Cordova.js
- Cordova相机交互代码