How can I send requests to JSON?

喜你入骨 提交于 2019-12-12 03:42:15

问题


I'm coding a mobile application with ionic. I have to get a data (daily changing data) from a web page with JSON, but I want to get old data too. For example:

data.json?date=2016-11-10
data.json?data=2016-12-10

How can I send request to JSON?


回答1:


To send data from PHP, once you get your data from the database, the array will apply json_encode($array); and to return you put return json_encode ($ array);

Try this!

var date = '2016-11-10';
$http({
       method: 'GET',
       url: data.php,
       params: {date: date},
       dataType: "json",
       contentType: "application/json"

 }).then(function(response) {

 });



回答2:


The question is confusing, so I'm not sure how to answer. If you are having trouble formatting a request to a REST service, you will need to find out how the service expects the date to be formatted in your field-value pair i.e:

date=2016/11/10 or date=20161110 

If those don't work, this answer may help The "right" JSON date format
However, if you are actually wondering how to serialize a date in JSON, this link may help http://www.newtonsoft.com/json/help/html/datesinjson.htm




回答3:


I prefer to use services for ajax requests.

Create a Service

//Service
(function() {
    'use strict';

    angular
        .module('appName')
        .factory('appAjaxSvc', appAjaxSvc);

    appAjaxSvc.$inject = ['$http', '$log', '$q'];

    /* @ngInject */
    function appAjaxSvc($http, $log, $q) {

        return {
            getData:function (date){

              //Create a promise using promise library
                var deferred = $q.defer();

                $http({
                    method: 'GET', 
                    url:'/url?date='+date
                }).
                success(function(data, status, headers,config){
                    deferred.resolve(data);
                }).
                error(function(data, status, headers,config){
                    deferred.reject(status);
                });

                return deferred.promise;
            },
        };
    }
})();

Then Use it in Controller

(function() {

    angular
        .module('appName')
        .controller('appCtrl', appCtrl);

    appCtrl.$inject = ['$scope', '$stateParams', 'appAjaxSvc'];

    /* @ngInject */
    function appCtrl($scope, $stateParams, appAjaxSvc) {
        var vm = this;
        vm.title = 'appCtrl';

        activate();

        ////////////////

        function activate() {

            appAjaxSvc.getData(date).then(function(response) {
                //do something
            }, function(error) {
                alert(error)
            });

        }
    }
})();


来源:https://stackoverflow.com/questions/40048960/how-can-i-send-requests-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!