读取和写入AngularJS中的服务器端文件

时间:2021-07-14 15:27:41

I'm attempting to create a simple guestbook with AngularJS, and read and write the names to a simple file. Trouble is, I can't seem to get my code to even read from the file.

我正在尝试使用AngularJS创建一个简单的留言簿,并将名称读写到一个简单的文件中。麻烦的是,我似乎无法让我的代码甚至从文件中读取。

This is my directory structure:

这是我的目录结构:

读取和写入AngularJS中的服务器端文件

This is index.html:

这是index.html:

<!DOCTYPE html>
<html ng-app>
    <head>
        <meta charset="ISO-8859-1">
        <title>GuestBook</title>
        <script src="http://code.angularjs.org/angular-1.0.0rc3.min.js"></script>
        <script type="text/javascript" src="javascript/user.js"></script>
    </head>
    <body>
        <h1>Welcome!</h1>
        <div ng-controller="UserCtrl">
            <ul class="unstyled">
                <li ng-repeat="user in users">
                    {{user}}
                </li>
            </ul>
        </div>
    </body>
</html>

This is user.js (Based off this question/answer):

这是user.js(基于这个问题/答案):

function UserCtrl($scope) {

    $scope.users = $(function() {
        $.get('data/users', function(data) {
            var array = data.split(',');
            console.log(array);
        });
    });
}

And this is my users file:

这是我的用户文件:

John,Jacob,James

I'm expecting this outcome:

我期待这个结果:

Welcome!

  • John
  • 约翰
  • Jacob
  • 雅各
  • James
  • 詹姆士

But instead, all I get is:

但相反,我得到的只是:

Welcome!

So my question is, how can I populate $scope.users with the names in the users file?

所以我的问题是,如何使用users文件中的名称填充$ scope.users?

I know I've got my AngularJS set up correctly because I was able to get the desired result when I hard-coded it:

我知道我已经正确设置了AngularJS,因为当我对其进行硬编码时,我能够获得所需的结果:

$scope.users =[John,Jacob,James];

I've also spent a lot of time googling and searching Stack Overflow for how to read and write to a file with JavaScript and/or AngularJS, but:

我还花了很多时间谷歌搜索和搜索Stack Overflow如何使用JavaScript和/或AngularJS读取和写入文件,但是:

  1. No one seems to be trying to do exactly what I'm trying to do;
  2. 似乎没有人试图做我正在做的事情;
  3. The instructions are either confusing or not really applicable to what I'm trying to do.
  4. 这些说明要么令人困惑,要么不适用于我正在尝试做的事情。

I'm also not sure where to begin to write code that will persist names to the users file -- but I'll be happy if I can just read the file for now, and ask how to write to it later in a separate question. (But extra gratitude if you do also show me how to write to it.)

我也不确定从哪里开始编写将名称保存到用户文件的代码 - 但如果我现在可以只读取该文件,我会很高兴,并在稍后的单独问题中询问如何写入该文件。 (但如果你也告诉我如何写它,还要特别感激。)

4 个解决方案

#1


4  

Try injecting angular's $http service into your controller first of all. And make sure you add a '/' before your 'data/users' path. (/data/users)

首先尝试将angular的$ http服务注入您的控制器。并确保在“数据/用户”路径之前添加“/”。 (/数据/使用者)

function UserCtrl($scope, $http) {
    $scope.users = [];
    $http.get('/data/users')
        .success(function(data, status, headers, config) {
            if (data && status === 200) {
                $scope.users = data.split(',');
                console.log($scope.users);
            }
        });
    });
}

You can check your console to see what kind of data is being returned. (Network tab)

您可以检查控制台以查看返回的数据类型。 (网络标签)

edit: just realized the $(function ... part didn't make sense.

编辑:刚刚意识到$(功能......部分没有意义。

#2


2  

The problem with your code is in this stub -

您的代码存在问题 -

$scope.users = $(function() {
    $.get('data/users', function(data) {
        var array = data.split(',');
        console.log(array);
    });
});

Here $scope.users is not the array variable. Instead, it is whatever $() returns. Your anonymous function is passed only as a parameter to $ function.

这里$ scope.users不是数组变量。相反,它是$()返回的。您的匿名函数仅作为参数传递给$ function。

Rewrite your controller this way -

以这种方式重写你的控制器 -

function UserCtrl($scope, $http) {
    $scope.users = [] // Initialize with an empty array

    $http.get('data/users').success(function(data, status, headers, config) {
        // When the request is successful, add value to $scope.users
        $scope.users = data.split(',')
    })
}

And now, since you have

现在,既然你有

<li ng-repeat="user in users">
    {{user}}
</li>

in your view, angular will set up a watch on $scope.users variable. If the value of $scope.users changes anytime in the future, angular will automatically update the view.

在您的视图中,angular将在$ scope.users变量上设置监视。如果$ scope.users的值在将来的任何时间发生更改,则angular将自动更新视图。

EDIT -

编辑 -

Along with the above edit, you need to make sure all the files are being served via a web server on the same host:port. Browsers limit AJAX access to another domain:port. Here is a quick way to do start a http server -

除上述编辑外,您还需要确保通过同一主机上的Web服务器提供所有文件:端口。浏览器限制对另一个域的AJAX访问:端口。这是一个快速启动http服务器的方法 -

Go to the project directory using terminal and type in

使用终端转到项目目录并输入

python -m SimpleHTTPServer for python

python -m用于python的SimpleHTTPServer

or

要么

ruby -run -e httpd -- -p 8000 . for ruby.

ruby -run -e httpd - -p 8000。对于红宝石。

Both will start a basic HTTP server at port 8000, serving content from that particular directory. Having done this, your index.html will be at http://localhost:8000/index.html and your data file should be accessibe as http://localhost:8000/data/user.js (your javascript can still use /data/user.js).

两者都将在端口8000启动基本HTTP服务器,从该特定目录提供内容。完成此操作后,您的index.html将位于http:// localhost:8000 / index.html,您的数据文件应为accessibe,如http:// localhost:8000 / data / user.js(您的javascript仍可使用/数据/ user.js的)。

#3


0  

It turns out I can't do what I'm trying to do the way I'm trying to do it. JavaScript by itself can't read files on the Server-Side, only on the Client-Side. To read and persist data, JavaScript has to make calls to a "Back-end" or server, written in something like Java, which isn't just a Browser scripting language.

事实证明,我不能做我正在尝试做的事情。 JavaScript本身无法读取服务器端的文件,只能在客户端读取。为了读取和保存数据,JavaScript必须调用“后端”或服务器,用Java编写,这不仅仅是一种浏览器脚本语言。

#4


0  

you entered 'users' instead of 'users.txt' as filename.

您输入'users'而不是'users.txt'作为文件名。

This works just fine to me:

这对我来说很好:

function UserCtrl($scope, $http) {
    $scope.users = []
    $http.get('data/users.txt').success(function(data, status, headers, config) {
        $scope.users = data.split(',')
    })}

#1


4  

Try injecting angular's $http service into your controller first of all. And make sure you add a '/' before your 'data/users' path. (/data/users)

首先尝试将angular的$ http服务注入您的控制器。并确保在“数据/用户”路径之前添加“/”。 (/数据/使用者)

function UserCtrl($scope, $http) {
    $scope.users = [];
    $http.get('/data/users')
        .success(function(data, status, headers, config) {
            if (data && status === 200) {
                $scope.users = data.split(',');
                console.log($scope.users);
            }
        });
    });
}

You can check your console to see what kind of data is being returned. (Network tab)

您可以检查控制台以查看返回的数据类型。 (网络标签)

edit: just realized the $(function ... part didn't make sense.

编辑:刚刚意识到$(功能......部分没有意义。

#2


2  

The problem with your code is in this stub -

您的代码存在问题 -

$scope.users = $(function() {
    $.get('data/users', function(data) {
        var array = data.split(',');
        console.log(array);
    });
});

Here $scope.users is not the array variable. Instead, it is whatever $() returns. Your anonymous function is passed only as a parameter to $ function.

这里$ scope.users不是数组变量。相反,它是$()返回的。您的匿名函数仅作为参数传递给$ function。

Rewrite your controller this way -

以这种方式重写你的控制器 -

function UserCtrl($scope, $http) {
    $scope.users = [] // Initialize with an empty array

    $http.get('data/users').success(function(data, status, headers, config) {
        // When the request is successful, add value to $scope.users
        $scope.users = data.split(',')
    })
}

And now, since you have

现在,既然你有

<li ng-repeat="user in users">
    {{user}}
</li>

in your view, angular will set up a watch on $scope.users variable. If the value of $scope.users changes anytime in the future, angular will automatically update the view.

在您的视图中,angular将在$ scope.users变量上设置监视。如果$ scope.users的值在将来的任何时间发生更改,则angular将自动更新视图。

EDIT -

编辑 -

Along with the above edit, you need to make sure all the files are being served via a web server on the same host:port. Browsers limit AJAX access to another domain:port. Here is a quick way to do start a http server -

除上述编辑外,您还需要确保通过同一主机上的Web服务器提供所有文件:端口。浏览器限制对另一个域的AJAX访问:端口。这是一个快速启动http服务器的方法 -

Go to the project directory using terminal and type in

使用终端转到项目目录并输入

python -m SimpleHTTPServer for python

python -m用于python的SimpleHTTPServer

or

要么

ruby -run -e httpd -- -p 8000 . for ruby.

ruby -run -e httpd - -p 8000。对于红宝石。

Both will start a basic HTTP server at port 8000, serving content from that particular directory. Having done this, your index.html will be at http://localhost:8000/index.html and your data file should be accessibe as http://localhost:8000/data/user.js (your javascript can still use /data/user.js).

两者都将在端口8000启动基本HTTP服务器,从该特定目录提供内容。完成此操作后,您的index.html将位于http:// localhost:8000 / index.html,您的数据文件应为accessibe,如http:// localhost:8000 / data / user.js(您的javascript仍可使用/数据/ user.js的)。

#3


0  

It turns out I can't do what I'm trying to do the way I'm trying to do it. JavaScript by itself can't read files on the Server-Side, only on the Client-Side. To read and persist data, JavaScript has to make calls to a "Back-end" or server, written in something like Java, which isn't just a Browser scripting language.

事实证明,我不能做我正在尝试做的事情。 JavaScript本身无法读取服务器端的文件,只能在客户端读取。为了读取和保存数据,JavaScript必须调用“后端”或服务器,用Java编写,这不仅仅是一种浏览器脚本语言。

#4


0  

you entered 'users' instead of 'users.txt' as filename.

您输入'users'而不是'users.txt'作为文件名。

This works just fine to me:

这对我来说很好:

function UserCtrl($scope, $http) {
    $scope.users = []
    $http.get('data/users.txt').success(function(data, status, headers, config) {
        $scope.users = data.split(',')
    })}