gpt4 book ai didi

javascript - 将 php 变量传递给 angular

转载 作者:可可西里 更新时间:2023-11-01 13:40:00 28 4
gpt4 key购买 nike

我正在构建一个 web 应用程序,这是我第一次使用 angular。我昨天尝试从 API 获取数据,但由于跨源资源限制,它无法在 Angular 中使用。幸运的是,我可以通过 PHP 中的简单 CURL 请求获取 json 日期。

所以我现在在这里。我在 PHP 变量中有 JSON 数据,想在我的 Angular 应用程序中使用这些数据。我怎样才能做到这一点?有没有办法将数据直接传递给 Angular ?或者我应该用 php 创建一个 json 文件,然后将它加载到我的函数中吗?你有什么建议?

我想用 php 变量 $content 的内容填充 $scope.posts。

这是PHP代码:

<?php


/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$returned_content = get_data('http://fingerzeig.ch/api/agenda/list');
$content = json_decode($returned_content);
//print_r ($content);

//Get first title
//$firstitle = $content[0] -> ID;

//print_r($firstitle);



?>

Angular 代码:

//MYAPP

var app = angular.module("MyApp", []);


app.controller("PostsCtrl", function($scope, $http) {
$http.get(' WHAT SHOULD GO HERE? ').
success(function(data, status, headers, config) {
console.log("success!");
console.log(data);
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});

最佳答案

您可以使用 apache 和 php 提供端点以从您自己的服务器获取此数据:

$http.get('/endpoint', function () { ... });

您还可以执行某些操作,有时称为将数据“引导”到 DOM 中。这工作正常 - 我通常这样做是为了确保单页应用程序的第一页加载不需要等待初始数据。第一个页面加载的所有内容都在服务器上设置并呈现到页面中以供应用程序收集,而无需发出进一步的请求:

为此,您可以像这样在窗口或全局范围内创建一个集合:

window.myPostData = "<?php echo $data; >";

随后在您的应用程序中,您通常可以期望窗口对象(或任何全局变量)始终在浏览器中可用,因此可以像这样访问它:

app.controller("PostsCtrl", function($scope) {
var posts = window.myPostData;
});

但是,您可能还希望能够访问新数据,因此您可能会尝试这样的操作:

// If $data is empty, set myPostData to false.
window.myPostData = <?php echo empty($data) ? 'false' : $data; >;

...

app.controller("PostsCtrl", function($scope, $http) {
var posts = window.myPostData;

// Set myPostData to false so future use of this controller during this
// request will fetch fresh posts.
window.myPostData = false;

// Now if we didn't bootstrap any posts, or we've already used them, get them
// fresh from the server.
if (!posts) {
$http.get('/endpoint', function() {
...
});
}
});

请注意,如果您不了解如何使用 apache 和 php 设置端点,您将只想坚持将数据引导到窗口或全局变量上。这并不理想,但它会起作用。

关于javascript - 将 php 变量传递给 angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com