标签: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]; }
- (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>
Hybrid--WebView中使用Ajax,布布扣,bubuko.com
标签:ajax javascript uiwebview hybrid xmlhttprequest
原文地址:http://blog.csdn.net/xunyn/article/details/38389247