栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

基本的Ajax使用node.js发送/接收

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基本的Ajax使用node.js发送/接收

  1. 您的请求应该发送到服务器,而不是实例化它的server.js文件。因此,该请求应如下所示:

    xmlhttp.open("GET","http://localhost:8001/", true);
    此外,您正在尝试为前端(index.html)提供服务,并以相同的URI提供AJAX请求。为此,您将必须在server.js中引入逻辑,以区分AJAX请求和常规http访问请求。为此,您将需要引入GET / POST数据(即call
    http://localhost:8001/?getstring=true
    ),或者对AJAX请求使用不同的路径(即call
    http://localhost:8001/getstring
    )。然后,在服务器端,您需要检查请求对象以确定在响应上写什么。对于后一种选项,您需要使用“ url”模块来解析请求。

  2. 您正在正确调用,

    listen()
    但错误地编写了响应。首先,如果您希望在导航到http:// localhost:8001 /时提供index.html ,则需要使用
    response.write()
    或将文件内容写入响应中
    response.end()
    。首先,您需要包括
    fs=require('fs')
    以访问文件系统。然后,您需要实际提供文件。

  3. 如果您异步使用XMLHttpRequest,则需要指定一个回调函数(已完成,第三个参数= true),并且想对响应做一些事情。您现在拥有的方式

    string
    将是
    undefined
    (或可能是
    null
    ),因为该行将在AJAX请求完成之前执行(即responseText仍然为空)。如果同步使用它(第三个参数= false),则可以编写内联代码。不建议这样做,因为它会在请求期间锁定浏览器。异步操作通常与onreadystatechange函数一起使用,该函数一旦完成就可以处理响应。您需要学习XMLHttpRequest的基础知识。从 这里 开始。

这是一个包含以上所有内容的简单实现:

server.js:

var http = require('http'),      fs = require('fs'),     url = require('url'), choices = ["hello world", "goodbye world"];http.createServer(function(request, response){    var path = url.parse(request.url).pathname;    if(path=="/getstring"){        console.log("request recieved");        var string = choices[Math.floor(Math.random()*choices.length)];        console.log("string '" + string + "' chosen");        response.writeHead(200, {"Content-Type": "text/plain"});        response.end(string);        console.log("string sent");    }else{        fs.readFile('./index.html', function(err, file) {   if(err) {       // write an error response or nothing here       return;   }   response.writeHead(200, { 'Content-Type': 'text/html' });   response.end(file, "utf-8");          });    }}).listen(8001);console.log("server initialized");

前端(index.html的一部分):

function newGame(){   guessCnt=0;   guess="";   server();   displayHash();   displayGuessStr();   displayGuessCnt();}function server(){   xmlhttp = new XMLHttpRequest();   xmlhttp.open("GET","http://localhost:8001/getstring", true);   xmlhttp.onreadystatechange=function(){         if (xmlhttp.readyState==4 && xmlhttp.status==200){string=xmlhttp.responseText;         }   }   xmlhttp.send();}

您需要对AJAX感到满意。使用mozilla学习中心学习XMLHttpRequest。使用基本的XHR对象后,您很可能希望使用一个良好的AJAX库,而不是手动编写跨浏览器的AJAX请求(例如,在IE中,您将需要使用ActiveXObject而不是XHR)。jQuery中的AJAX非常好,但是如果您不需要

更新:我在上面的代码中已更改

response.sendHeader()
为新
response.writeHead()
代码!!!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464749.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号