How can I send requests to JSON?

2019-09-12 09:20发布

问题:

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

        }
    }
})();