【发布时间】:2016-05-30 20:10:31
【问题描述】:
我想以字符串格式显示名称,但 Main.html 页面没有从 session.json 页面读取值。所以请帮助我
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope, Session) {
$scope.name = 'World';
$scope.session = Session;
});
app.run(function(Session) {}); //bootstrap session;
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json')
.then(function(r) { return Session.data = r.data;})
}
};
Session.updateSession();
return Session;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
Welcome,
<pre ng-bind='session.data.username | json'></pre>
</body>
</html>
This is session.json page but in $http.get('session.json') it is not reading value from this page .
{ "username": "John Smith" }
如何从json页面读取字符串到main.html并显示
【问题讨论】:
-
document.write可以清除您现有的文档,至少在某些浏览器中是这样。不要使用它。 -
Session.data = r.data;r似乎未定义。您可能在控制台中有错误。 -
您的代码在 Firefox 浏览器中运行良好!然后我在 chrome 浏览器中尝试它在读取 session.json 文件时抛出 xmlhttprequest 错误,这意味着,您正在尝试将 session.json 作为文件加载,协议 chrome 不允许此操作(网络安全)。无论如何,我的问题是您是否在任何服务器环境中运行您的代码?如果您在服务器环境中运行此代码,它应该可以工作。顺便说一句,您也可以尝试像“chrome.exe --disable-web-security”这样启动您的 chrome 浏览器,这将禁用 chrome 网络安全并可以访问文件。告诉我。
标签: angularjs