利用nodejs搭建伺服器,測試AJAX

來源:互聯網
上載者:User

標籤:

     最近學習了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>

測試一下:

                                                                                                                                                                                             

一個簡單的小測試就成功了。

 

利用nodejs搭建伺服器,測試AJAX

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.