Is there a method in angularJS thats equal to getJSON. [Newbie alert]

邮差的信 提交于 2019-12-01 04:38:19

Because of the help i got from people answering my question I finally managed to fix it, and i did it like this:

app.controller('myController', function($scope, $http){
    $scope.items = [];  
     $scope.search = function() {        
            $http({method: 'JSONP', url: "http://something.com/lol?callback=JSON_CALLBACK&query="+ $scope.searchString}).
              success(function(data, status) {
                $scope.items = data.entries;
              }).
              error(function(data, status) {
                console.log(data || "Request failed");
            });     
     };

Hope this helps anyone who has the same problem in the future :D

You could use $http to send AJAX requests in Angular.

Vikash Pathak

You may use JSONP requests with $http.jsonp

https://docs.angularjs.org/api/ng/service/$http#jsonp

function ListProdcutsCtrl($scope, $http) {
    var request = {'searchString' : 'apple'};
    $http.get('/api/products', request).success(function(response) {
        $scope.products_table_data = response.products;
    });

There is an alternative in AngularJS called $http, you can find more here. For instance :

$http({method: 'JSONP', url: 'http://domain.com/page?json_callback=JSON_CALLBACK'}).success(
    function(data, status) {
        // your stuff.
    }
);

Or even shorter :

$http.jsonp('http://domain.com/page?json_callback=JSON_CALLBACK').success(
    function(data, status) {
        // your stuff.
    }
);

JSONP (JSON Padding) allows you to get JSON data from another domain. However, the data you get should not be plain JSON, but rather a Javascript file like this :

JSON_CALLBACK([
    {"name": "apple", "color": "red"},
    {"name": "banana", "color": "yellow"}
]);

If your JSON data you need comes from the same domain, you do not need JSONP.

JSONP is used to overcome the cross-domain restriction of the AJAX URL calls.

With AngularJS (v1.5), you can use this code to send cross domain requests:

$http.jsonp(baseurl+'?token=assume_jwt_token'+encoding+type + "&callback=JSON_CALLBACK")

The Syntax for AngularJS JSONP request is :

$http.jsonp(url, [config]);

where url is "string" type representing Relative or absolute URL specifying the destination of the request. The name of the callback should be the string JSON_CALLBACK, and [config] is Optional configuration object.

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