Hybrid--WebView中使用Ajax

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.