当前位置:首页 > Web开发 > 正文

内容简陋请多包含....... 前端html代码: html head metacharset="UTF-8" titl

2024-03-31 Web开发

第一次颁布内容,内容简陋请多包罗.......

前端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=="http://www.mamicode.com/"){

        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);



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

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32622.html