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

nodejs ajax 基础-jQuery实现

2017-12-04 22:03 369 查看
index.js
:

var http = require('http')
var url = require('url')
var path = require('path')
var util = require('util')
var qs = require('querystring')
var fs = require('fs')
http.createServer(function (req, res) {
switch (req.url) {
case '/test1.js':
res.writeHead(200, {
'Content-Type': 'text/javascript'
})
res.end(fs.readFileSync('./test1.js'))
break;

case '/data.txt':
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end(fs.readFileSync('./data.txt'))
default:
res.writeHead(200, {
'Content-Type': 'text/html'
})
res.end(fs.readFileSync('./index.html'))
//res.end(obj.name)
break;
}

}).listen(8000)

var sendFile = function (res, filePath, mime) {
res.writeHead(200, {
'Content-Type': mime
})
res.write(fs.readFileSync(filePath))
}
console.log('listen at ' + 8000)


index.html
:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="./test1.js"></script>
</head>
<body>
<p>show here</p>
<button>click</button>
</body>
</html>


test1.js
:使用jquery.ajax实现

window.onload=function(){
//alert('hah')
$('button').click(function(){
var xml=$.ajax({
url:'/data.txt',
async:false
})
$('p').text(xml.responseText)
})
}


data.txt
:

hello this is a test file
so ...
you konw just say something
like  666


node index.js
后访问http://127.0.0.1:8000,返回页面,点击按钮,上方段落内容会变为服务端data.txt的内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery ajax nodejs