javascript 将 php 变量传递给 angular

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26917889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:40:49  来源:igfitidea点击:

Passing a php variable to angular

javascriptphpjsonangularjscurl

提问by elpeyotl

I am building a webapp and I'm using angular for the first time. I tried yesterday to get data from an API but it will not work in Angular cause of cross origin resource restrictions. Lucky I can get the json date over a simple CURL request in PHP.

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

So here I am now. I have the JSON Data in a PHP Variable and want to use this data in my Angular Application. How can I achieve that? Is there a way to pass the data directly to angular? Or should i create a json file with php and then load it into my funcion? What suggestions do you have?

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

I want to fill the $scope.posts with the content of the php variable $content.

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

Here's the php code:

这是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);



        ?>

The Angular code:

角度代码:

//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
    });
});

回答by Steve Adams

You could provide and endpoint using apache and php to get this data from your own server:

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

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

You could also do something sometimes referred to as 'bootstrapping' data into the DOM. This works fine - I typically do it to ensure the first page load of a single page app doesn't require waiting on initial data. Everything for the first page load is set up on the server and rendered into the page for the app to collect without making further requests:

你也可以做一些有时被称为“引导”数据到 DOM 的事情。这很好用 - 我通常这样做是为了确保单页应用程序的第一页加载不需要等待初始数据。第一个页面加载的所有内容都在服务器上设置并呈现到页面中以供应用程序收集而无需进一步请求:

To do this, you can create a collection on the window or global scope like this:

为此,您可以在窗口或全局范围内创建一个集合,如下所示:

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

Then later in your app, you can typically expect the window object (or any global variable) to be available in the browser at all times so it'll be accessible like this:

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

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

However, you probably want to be able to access fresh data as well, so you'd probably try something like this:

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

// 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() {
            ...
        });
    }
});

Mind you, if you don't have the understanding of how to set up an endpoint using apache and php, you will want to stick with only bootstrapping the data onto the window or a global variable. It's not ideal, but it would work.

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

回答by elpeyotl

Thank you everybody for your help. It is working and the solution was very simple.

谢谢大家的帮助。它正在工作,解决方案非常简单。

I created a variable in Javascript which gets the returned content of PHP.

我在 Javascript 中创建了一个变量,它获取 PHP 的返回内容。

var thedata = <?php echo $returned_content;?>;

Then i put this variable in my angular app file:

然后我把这个变量放在我的 angular 应用程序文件中:

//MYAPP

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

app.controller("PostsCtrl", function($scope) {
  $scope.posts = thedata;
  console.log(thedata);
});

I can access this data now in my ng-repeat.

我现在可以在我的 ng-repeat 中访问这些数据。

<body ng-app="MyApp">
  <div ng-controller="PostsCtrl">
    <ul ng-repeat="post in posts">
      <li>{{post.ID}}</li>
    </ul>
  </div>
</body>

It works sweet! Very simple solution.

它的工作很甜蜜!非常简单的解决方案。

回答by creanium

Since you're already getting JSON data, just output the JSON data. No need to do json_decode.

由于您已经在获取 JSON 数据,因此只需输出 JSON 数据。不需要做 json_decode。

So just echo $returned_content

所以就 echo $returned_content

Edit:

编辑:

The part where you have $http.get(' WHAT SHOULD GO HERE? ')in your Angular code should point to the relative URL of the PHP page. e.g. If your PHP page is accessed at http://server.com/webapp/get_data.phpthen your angular would be $http.get('/webapp/get_data.php')

$http.get(' WHAT SHOULD GO HERE? ')在 Angular 代码中的部分应该指向 PHP 页面的相对 URL。例如,如果您的 PHP 页面被访问,http://server.com/webapp/get_data.php那么您的角度将是$http.get('/webapp/get_data.php')

回答by Mutmatt

You could just force it on to the scope like this, not sure if it is best practice but ya... Or you could have your angular controller call to a php function in an

你可以像这样将它强加到范围上,不确定这是否是最佳实践,但是你......或者你可以让你的角度控制器调用一个 php 函数

$http.get('func').then(function(data) {
//do stuff
});

or just shove it on scope

或者只是把它推到范围内

<input ng-model="myContent" value="<?php echo $returned_content?>"/>