ajax訪問Node服務器

前言:node算是入了個門。現在終於有個服務器。以前只寫過SSH框架的java後臺下,前臺使用jquery交互。但是純原生怎麼寫呢?

demo需求

既然是demo先從最簡單的。書寫一個表單提交頁面。從前臺input提交到後臺,接收輸出到瀏覽器。後臺將收到的數據再展示到前臺output中。
雙向的數據傳輸demo。demo雖小,五臟俱全。

新建工程

idea開發。新建基礎模版。

前臺頁面index.html

頁面實現如下:

這裏寫圖片描述

<h3>請填寫下表</h3>
<form>
    <label>姓名:<input type="text" id="name" name="name" value="zyd317"></label>
<br><br>
    <input type="submit" value="提交">
<br><br>
    您的姓名是:<output id="output"></output>
</form>
<script>
    var name = document.getElementById("name").value;
    var output = document.getElementById("output");
    //alert(name);
    var xhr = new XMLHttpRequest();
    xhr.open("get","http://localhost:8888/?name="+name,true);//把數據傳到哪裏?
    xhr.onreadystatechange=function () {
        if(xhr.readyState==4){
            if(xhr.status>=200&&xhr.status<300||xhr.status==304){
                console.log("您的名字是:"+xhr.responseText);//從服務器得到的反饋文本
                output.innerHTML=xhr.responseText;

            }
        }
    };
    //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send();//表單必須要要格式化
</script>

node後臺index.js

var http = require("http");//獲取http模塊
    function onRequest(req,res) {//定義服務器監聽得到響應的函數
        var text = req.url.toString().split("=")[1];
        console.log("result-----------"+req.url.toString());
        console.log("text-----------"+text);
        res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"http://localhost:63342"});
        res.write(text);//相當於頁面的responseText
        res.end();
    }
http.createServer(onRequest).listen(8888, function () {//createServer可以傳入兩個參數(req,res)
    console.log("listening................");
});

後臺打印:
這裏寫圖片描述

技術要點

1,idea的nodejs項目的配置。添加nodejs的plugin–>導入新建的nodejs工程–>配置,Node.js導入Index.js即可
2,http模塊的引用
3,解析http中的url字段。req.url.toString().split(“=”)[1] 我這裏使用的個人感覺比較複雜。。愚鈍。。未找到更好的方法。等日後多瞭解一些node再來修改。
4,response,request的設置。包括Nodejs中和前臺JavaScript中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章