首页 > 代码库 > Hybrid--WebView中使用Ajax
Hybrid--WebView中使用Ajax
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 = http://www.mamicode.com/b.split('?');>其中的"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个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。