【问题标题】:Simple script using ajax and node.js, why it don't work?使用 ajax 和 node.js 的简单脚本,为什么它不起作用?
【发布时间】:2014-05-27 18:36:46
【问题描述】:

我有html页面:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script type="text/javascript">
        function pushMe(elem) {            
            var request = new XMLHttpRequest();               

            if (!request) alert("Error initializing XMLHttpRequest!");

            request.open('GET', 'proj1.js', true);

            request.onreadystatechange = function () {
                if (request.readyState == 4)
                    elem.value = request.responseText;
            };         
            elem.value = '...';
            request.send(null);   
        }
    </script>
</head>
<body>
    <input type="button" onclick="pushMe(this);" value="Push Me!" id="btn"/>
</body>
</html>

和js文件(proj1.js):

var http = require('http');
var url = require('url');
var querystring = require('querystring');

function accept(req, res) {

    res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Cache-Control': 'no-cache'
    });

    res.end("HELLO!");
}

http.createServer(accept).listen(8080);

proj1.js 和 test.html 在同一个文件夹中。 为什么当我单击按钮时按钮的值不会改变? (它改变了,但是 request.responseText 是空的,为什么它不是“HELLO!”?)

【问题讨论】:

  • 控制台上有任何错误信息吗?你检查过网络标签吗?你添加断点了吗?请进行一些调试并在此处发布您的结果
  • 你在服务器上预先安装Node.js成功了吗?
  • 嗨!我的回答解决了你的问题?如果是,请检查为“正确”,如果不是,请告诉我缺少什么。

标签: javascript ajax node.js


【解决方案1】:

你的问题:

您正在使用文件协议中的文件,例如:

file:///c:\user\index.html

并试图访问在HTTP 上运行的服务器,这是不可能的(除非您释放浏览器的安全权限,但事实并非如此)。

正确的是您在 HTTP 脚本上运行 Ajax。

了解基础知识

在开始 Web 编程之前,您应该了解什么是 HTTPWebServerClientProtocolRequestResponseStatus Code

Node.js 入门:

http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

[已编辑]

可能的问题:

  • 调用的端口不正确(可能不是使用端口 8080,ajax 调用的是端口 80)

脚本中的问题:

  • Http 错误未处理(您的 ajax 未处理 http 错误)

试试这个:

        request.open('GET', 'proj1.js', true);

        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    elem.value = request.responseText;
                } else {
                    elem.value = "Error:" + request.status;//Get error
                }
            }
        };

使用控制台/网络工具

按 F12(例如 firefox),查看选项卡“网络”和“控制台”:

使用开发者工具:

【讨论】:

  • 第一个问题,我觉得第二个没有意义
  • @MamekoMikhail 您在浏览器中使用了“F12”键(开发人员工具)? console.log 返回了什么?你能用console.log吗?您是否检查了前端用于请求您的服务器的端口?
  • NS_ERROR_NOT_INITIALIZED: file:///C:/.../test.html 第 22 行
  • @MamekoMikhail 您无法在“文件协议”中调用相关文件,并且浏览器知道您想要捕获“http”服务器。
  • @MamekoMikhail 您无法从本地文件运行 AJAX。您必须从您的localhost 地址运行它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多