使用Angular JS为WordPress JSON API使用JSON操作数据

时间:2015-03-28 18:25:26

标签: javascript json angularjs api

我在this post中测试了代码并修改了一下供我使用。但我无法从我使用WordPress JSON插件生成的博客API中获取JSON对象。

  1. 来自BLOG(不工作)的URL API:http://teckstack.com/api/get_recent_posts
  2. 来自W3C示例(工作)的网址:http://www.w3schools.com/website/Customers_JSON.php
  3. 我试图从我的博客(上面提到的)操纵JSON API时遇到困难,并且相同的代码适用于w3c示例提供的其他网址?

    请提供您的建议。

    我在 .html文件中使用以下代码,而不是在WordPress环境中使用

    ==== Angular JS脚本 ====

    (function() {
        var app = angular.module('tsApp', []);
        app.controller('TSController', function($scope, $http) {
            $scope.heading = [];
            $http({
                method: 'GET',
                url: 'http://teckstack.com/api/get_recent_posts'
            }).success(function(data) {
                console.log("pass");
                $scope.heading = data; // response data 
            }).error(function(data) {
                console.log("failed");
            });
        });
    })();
    

    ==== HTML ====

    <html ng-app="tsApp">
    <body ng-controller="TSController as tsCtrl">
            <article class="main-content" role="main">
                <section class="row">
                    <div class="content">
                        <div class="name-list">
                            <h1>Dummy Title</h1>
                            <ul>{{ 1+1 }} (Testing AJS is working)
                                <li ng-repeat="title in heading" class="">
                                    <h3>{{title.Name}}</h3>
                                </li>
                            </ul>
                        </div>
                    </div>
                </section>
            </article>
            <script type="text/javascript" src="js/main.js"></script>
        </body>
    </html>
    

    我在线检查所有解决方案后提出这个问题 https://stackoverflow.com/a/26898082/1841647http://www.ivivelabs.com/blog/fix-cross-domain-ajax-request-angularjs-cors/ 但没有什么对我有用。

    为方便起见,创建JSFiddle: http://jsfiddle.net/236gdLnt/

1 个答案:

答案 0 :(得分:1)

这是一个跨域问题。您可以通过JSONP请求获取第一个网址数据。使用$http.jsonp方法角度support

$http.jsonp('http://teckstack.com/api/get_recent_posts?callback=JSON_CALLBACK')
   .success(function (data1) {
        console.log("BLOG pass");
        $scope.heading1 = data1; // response data 
    }).error(function (data1) {
        console.log("BLOG failed");
    });

确保将callback=JSON_CALLBACK参数添加到您的网址。