欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实现基于Node.js的ajax前后端交互的简单例子

程序员文章站 2024-03-23 17:25:16
...

前端代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajaxtest</title>
</head>

<body>
    <button onclick="ajax()">button</button>
</body>

<script src="jquery-1.9.1.js"></script>

<script>
    function ajax() {
        $.ajax({
            url: 'http://127.0.0.1:8080/',
            dataType: 'json',
            type: 'get',
            data: {
                test: 'ajax'
            },
            success: function (data) {
                console.log(data);
            }
        })
    };
</script>

</html>

后端代码:

var http = require('http');
var url = require('url');
var createServer = http.createServer(onRequest);

function onRequest(request, response) {
    response.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*'
    });
    var str = JSON.stringify(url.parse(request.url, true).query);
    response.write(str);
    response.end();
}
createServer.listen(8080);
console.log('Server running  at http://127.0.0.1:8080/');