JavaScript下Ajax与服务器之间的通信

来源:互联网 发布:电视直播 for mac 编辑:程序博客网 时间:2024/06/05 16:31

第一步:包含一个点击事件的HTML(事件触发Ajax与服务器通信)

<!doctype html><html>    <head>        <title>College Task</title>        <meta charset="utf-8" />            </head>    <script>        function Ajax(){            var req=null;            req=new XMLHttpRequest();            req.open('POST','http://127.0.0.1:8081/');//指定了传输数据的方式以及服务器所监听的端口            req.send('Hello Server');            req.onreadystatechange=function(){                if(req.readyState==4 && req.status==200){                    console.log(req.responseText);//接收服务器返回的数据                }            }        }       </script>    <body>        <input type='button' value='Click' onclick='Ajax()' />    </body></html>

第二步:服务器监听8081端口

var http=require('http');var server=http.createServer(function(req,res){    req.on('data',function(data){        console.log(data.toString());//接收到数据就在控制台打印    });    req.on('end',function(){});    res.setHeader("Access-Control-Allow-Origin", "*");      res.write('Hello Client');//回应给客户端的数据    res.end();}).listen(8081,function(){    console.log('Server is running');});

res.setHeader("Access-Control-Allow-Origin", "*"); 解决了跨域访问的问题,但是” * “让所有的跨域访问没有了限制,不可取。此处我这样使用是求个方便来测试Ajax
如果没有这一句会报错: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

提交数据到服务器有两种常用方式:提交表单和Ajax,为什么提交表单不会遇到跨域访问的问题呢,这是因为提交表单同时浏览器产生了跳转,不存在跨域了

所谓跨域就是,在a.com域下,访问b.com域下的资源;
出于安全的考虑,浏览器允许跨域写,而不允许跨域读,也就是可以发送请求(send request),但是不能接受响应(receive response)

原创粉丝点击