標籤:ajax javascript uiwebview hybrid xmlhttprequest
Hybrid架構下的app,使用的Ajax,需要注意的是UIWebViewDelegate不會監測到Ajax的request,也就是再執行Ajax代碼時,shouldStartLoadWithReuqest等方法並不會被調用。
其解決方案需要Javascript和navtive code一起來做,其基本原理可參考這片文章,其流程是在
Javascript handler中每建立Ajax的請求時,需要將這段js存在ajax_handler.js放在app中
var s_ajaxListener = new Object();s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;s_ajaxListener.callback = function () { window.location='mpAjaxHandler://' + this.url;};XMLHttpRequest.prototype.open = function(a,b) { if (!a) var a=''; if (!b) var b=''; s_ajaxListener.tempOpen.apply(this, arguments); s_ajaxListener.method = a; s_ajaxListener.url = b; if (a.toLowerCase() == 'get') { s_ajaxListener.data = b.split('?'); s_ajaxListener.data = s_ajaxListener.data[1]; }}XMLHttpRequest.prototype.send = function(a,b) { if (!a) var a=''; if (!b) var b=''; s_ajaxListener.tempSend.apply(this, arguments); if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a; s_ajaxListener.callback();}
其中的"mpAjaxHandler"為自訂的Scheme,用於區別request是否是由Ajax發出的。
在App端
獲得js
static NSString *JSHandler;+ (void)initialize { JSHandler = [[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"ajax_handler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil] retain];}
載入頁面後,執行這段js
- (void)webViewDidStartLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:JSHandler];}攔截住Request,不讓webview的URL做出改變
#define CocoaJSHandler @"mpAjaxHandler"- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ([[[request URL] scheme] isEqual:CocoaJSHandler]) { NSString *requestedURLString = [[[request URL] absoluteString] substringFromIndex:[CocoaJSHandler length] + 3]; NSLog(@"ajax request: %@", requestedURLString); return NO; } return YES;}
Ajax相關知識
Ajax作為非同步Javascript廣泛應用在web網站上。下面是一個來自於w3school的簡單使用Ajax的例子:
<html><head><script type="text/javascript">function loadXMLDoc(){var xmlhttp;var txt,x,i;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) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("title"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt; } }xmlhttp.open("GET","http://www.w3school.com.cn/example/xmle/books.xml",true);xmlhttp.send();}</script></head><body><h2>My Book Collection:</h2><div id="myDiv"></div><button type="button" onclick="loadXMLDoc()">GET Book List</button> </body></html>
點擊button,通過Ajax的方式獲得書單。部分內容參考於stackoverflow