您的位置:首页 > Web前端 > Node.js

实现基于Node.js的ajax前后端交互的简单例子

2017-06-17 22:06 1151 查看
前端代码:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ajaxtest</title>
</head>

<body>
<button onclick="ajax()">button</button>
</body>

<script src="jquery-1.9.1.js"></script>

<script>
function ajax() {
$.ajax({
url: 'http://127.0.0.1:8080/',
dataType: 'json',
type: 'get',
data: {
test: 'ajax'
},
success: function (data) {
console.log(data);
}
})
};
</script>

</html>


后端代码:

var http = require('http');
var url = require('url');
var createServer = http.createServer(onRequest);

function onRequest(request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
var str = JSON.stringify(url.parse(request.url, true).query);
response.write(str);
response.end();
}
createServer.listen(8080);
console.log('Server running  at ' target='_blank'>http://127.0.0.1:8080/');[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Node.js ajax