Android代码
package com.example.sss.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
//允许chrome://inspect调试
WebView.setWebContentsDebuggingEnabled(true);
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/demo.html");
}
}
node server.js
var http = require('http');
var URL = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
"access-control-allow-origin": "*",
});
res.end((parseInt(Math.random()*100)+""));
}).listen(8080);
console.log('Server running on port 8080.');
demo.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button type="button" onclick="loadText();">Load Text</button>
<div id="content"></div>
<script>
function loadText(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("get","http://192.168.20.177:8080",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
}
</script>
</body>
</html>
这种常见的混合模式App开发中,js并不能访问到后台。那么到底是怎么通信的呢。答案:代理。
网友评论