zoukankan      html  css  js  c++  java
  • 利用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>

    测试一下:

                                                                                                                                                                                                 

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

  • 相关阅读:
    HDU 1069 Monkey and Banana
    HDU 1029 Ignatius and the Princess IV
    HDU 1024 Max Sum Plus Plus
    Gym100923H Por Costel and the Match
    Codeforces 682C Alyona and the Tree
    Codeforces 449B Jzzhu and Cities
    Codeforces (ccpc-wannafly camp day2) L. Por Costel and the Semipalindromes
    Codeforces 598D (ccpc-wannafly camp day1) Igor In the Museum
    Codeforces 1167c(ccpc wannafly camp day1) News Distribution 并查集模板
    快乐数问题
  • 原文地址:https://www.cnblogs.com/coco-163/p/5714404.html
Copyright © 2011-2022 走看看