简体   繁体   English

如何将json文件用于静态服务器?

[英]How can I use a json file for a static server?

I have written a simple app in angular, where I have encoded the json data directly into the $scope of a controller, and then I do stuff with that data. 我用angular写了一个简单的应用程序,在其中将json数据直接编码到控制器的$scope中,然后使用该数据进行处理。 Can I have something like data.json, and send it to the client along with js and css files, which angular can then read? 我是否可以使用data.json之类的东西,并将其与js和css文件一起发送到客户端,然后可以读取哪个角度? How would I go about doing that? 我将如何去做? Ajax is not allowed. 不允许使用Ajax。

If AJAX is not allowed you will have to make the file a javascript file, not a JSON file. 如果不允许AJAX,则必须使该文件成为javascript文件,而不是JSON文件。 By doing this you get something very similar to JSONP (JSON with Padding). 通过这样做,您将获得与JSONP(带有填充的JSON)非常相似的东西。 In this, you essentially pass the JSON object to a callback function. 在此,您实际上将JSON对象传递给了回调函数。 For example: 例如:

myCallback({"foo":"bar", "bing":1900});

You can then include this file as a script tag and your callback will be fired with the appropriate data. 然后,您可以将该文件作为脚本标签包括在内,并且将使用适当的数据触发回调。 Ensure that you include the script tag for the data after the script tag that defines the callback function. 确保在定义回调函数的脚本标记之后包括数据的脚本标记。

The other alternative is storing the object as a global variable. 另一种选择是将对象存储为全局变量。 It's generally considered bad to pollute the global scope. 通常认为污染全球范围是不好的。

Local acces 本地配件

For local access only, ou could use file URI (maybe, depending on tools used): 仅对于本地访问,您可以使用文件URI(也许取决于所使用的工具):

file:///home/user/project/file.js

instead of 代替

http://somewhere.net/project/file.js

... ...

Sharing pages 分享页面

You have to use a server in order to serve files to browsers ( clients ). 您必须使用服务器才能将文件提供给浏览器( 客户端 )。

For doing this, the lighter prototypical way is to use tools like netcat : 为此,更简单的原型方法是使用诸如netcat之类的工具:

nc -l -p 8080 -q 0 < <(
    echo $'HTTP/1.1 200 OK\r\nContent-type: application/javascript\r\n\r';
    cat file.js)

even in a while true;do ... ;done loop. 即使是while true;do ... ;done循环。

You may use more featured prototypical tools like Mojolicious or finalized servers like lighttpd , nginx , Apache or else.. 您可以使用功能更强大的原型工具(例如Mojolicious)或定型服务器(例如lighttpdnginxApache或其他)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM