原生js使用ajax进行简单的前后端的数据交互|js&node&ajax

 第一次发布内容,内容简陋请多包含.......

前端html代码: 

<html>
    <head>
        <meta charset="UTF-8">
        <title>AJAX 实例</title>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
        <script>
            var data="data=sdd&hf=jkhklh"   // 要提交的数据

            // 使用ajax提交get方式数据
        function ajax(){
        var oAjax = new XMLHttpRequest();
        oAjax.onreadystatechange = function (){
        if(oAjax.readyState == 4&& oAjax.status == 200){
        alert(oAjax.responseText);
        }
        }
        oAjax.open('GET', '/ss?'+data);
        oAjax.send();
        }


        // 使用ajax提交post方式数据
        function ajaxP(){
        var oAjax = new XMLHttpRequest();
        oAjax.onreadystatechange = function (){
        if(oAjax.readyState == 4&& oAjax.status == 200){
        alert(oAjax.responseText);
        }
        }
        oAjax.open('POST', '/ss');
        oAjax.send(data);
        }
        </script>
    </head>
    

 <body>
      <button type="button" onclick="ajax()">Get</button>
      <button type="button" onclick="ajaxP()">Post</button>
    
    </body>
    
</html>
 
后端node.js代码:
var http = require("http");
var fs = require("fs");
var url=require("url");

var app=(req,res)=>{
    var pathname = url.parse(req.url).pathname;
    var method = req.method.toLowerCase();
    if(pathname=="/favicon.ico")return;
    if(pathname=="/"){
        fs.readFile("./ajax.html",(err,data)=>{
            res.writeHead(200,{'content-type':'text/html;charset=utf8'});
            res.end(data);
        })
    }
    if(pathname=="/ss"&&method=="get"){
        // console.log(url.parse(req.url).query);
        res.writeHead(200,{'content-type':'text/html;charset=utf8'});
        res.end('{"data":"这是GET数据"}');
    }
    if(pathname=="/ss"&&method=="post"){
        // console.log("sdsd");
        req.on("data",function(data){
            //打印
            // console.log(decodeURIComponent(data));
        });
        res.writeHead(200,{'content-type':'text/html;charset=utf8'});
        res.end('{"data":"这是POST的数据"}');
    }
    console.log(url.parse(req.url))
}

http.createServer(app).listen(8000);


猜你喜欢

转载自www.cnblogs.com/moope/p/12121997.html