利用nodejs搭建服务器,测试AJAX

     最近学习了AJAX一直没有进行过测试,前今天了解了Noejs搭建本地服务器下就尝试了一下。通过AJAX请求的方式获取HTTP服务器返回数据的代码

首先创建一个serve.js的文件。并写入以下代码.

 1 var http=require("http");
 2 
 3 var server=http.createServer(function(req,res){
 4 
 5     if(req.url!=="/favicon.ico"){
 6 
 7         res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"http://localhost:63342"});
 8 
 9         res.write("hello,我是从服务器端接收的")
10 
11     }
12 
13     res.end();
14 
15 });
16 
17 server.listen(8888,"localhost",function(){
18 
19     console.log("开始监听...");
20 
21 });

打开cmd进入相应的目录文件夹下,我的存在e盘的node-demo文件夹下,只需输入e:回车,cd node-demo 回车,最后 node serve.js,然后提示开始监听...,说明本地服务器已经搭建好了.

在webstorm(因为webstorm下已经配置好了服务器环境其默认端口为:63342)会比较简单,新建一个testAJAX.html文件具体代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>ajax demo</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link href="" rel="stylesheet">
</head>
<body>
<input type="button" value="点击一下" onclick="GetData()" />
<div id="test">
    this is a  ajax demo
</div>
</body>
<script>
    function GetData(){
        var xhr=new XMLHttpRequest();
        xhr.open("GET","http://localhost:8888",true);
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
            document.getElementById("test").innerHTML=xhr.responseText;
                }
            }
        }
        xhr.send(null);
    }
</script>
</html>

测试一下:

                                                                                                                                                                                             

一个简单的小测试就成功了。

 

posted on 2016-07-28 12:57  进击的coco  阅读(3057)  评论(0编辑  收藏  举报