【问题标题】:Manipulate Data with JSON using Angular JS for WordPress JSON API使用 Angular JS for WordPress JSON API 使用 JSON 操作数据
【发布时间】:2015-03-28 18:25:25
【问题描述】:

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

  1. 来自博客的 URL API(不工作):http://teckstack.com/api/get_recent_posts
  2. 来自 W3C 示例的 URL(工作):http://www.w3schools.com/website/Customers_JSON.php

当我试图从我的博客(上面提到)操纵 JSON API 时我卡住了,并且相同的代码适用于 w3c 示例提供的其他 url?

请提供您的建议。

我在 .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/

【问题讨论】:

    标签: javascript json angularjs api


    【解决方案1】:

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

    $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 参数添加到您的网址。

    【讨论】:

    • 我按照你的建议尝试了但没有工作:(。更新小提琴:jsfiddle.net/236gdLnt/1
    • 您没有切换到$http.jsonp 方法。检查这个小提琴:jsfiddle.net/8r17vcg7
    • 哦!愚蠢的错误。现在可以了。很大的帮助。你能告诉我具体的链接,它可以一步步指导使用AngularJS为HTML项目操作WordPress JSON API吗?
    • 一个重要的输入 - 如果存在跨源错误,那​​么我们可以使用 https://crossorigin.me/ 作为 API url 的前缀。 (即:https://crossorigin.me/http://teckstack.com/api/get_recent_posts?callback=JSON_CALLBACK
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 2017-09-10
    • 2017-08-09
    相关资源
    最近更新 更多