Angular $http.jsonp() method works only once

2019-08-14 04:36发布

问题:

Response is succeded (alert->done), but second and another hits will response 'error'.

I've tried to add some config params with 'cache: false' but still works only first time. Should I clear some cache/history or sth?

    $scope.add2 = function() {

    var config = {
        //url : 'http://www.***.pl/index.php/json/getallusers',
        cache: false,
        //type : 'POST',
        crossdomain: true,
        //callback: 'JSON_CALLBACK',
        //data: d,
        contentType: "application/json",
        dataType: "jsonp",
    };

            var r = Math.floor(Math.random() * 1000) + 4;
            var d = {user_type_id:0, user_venue_id:0, fname:r}; 
            var e = objToString(d);


//$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e, config)

$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e)
                .success(function(res){
                    console.log('res:' + res.user); 
                    alert('done');
                })
                .error(function(){  
                    console.log('error');       
                    alert('error');
                }); 
        };

This is the new question in jsonp and post action in ionic framework (angular.js)

I've added to server response 'angular.callbacks._0(' before json data... maybe here's mistake?

This is solution for my issue: now i'm dynamiccaly getting the callback parameter which can by vary (not always angular.callback_0, but can be: angular.callback_1, angular.callback_2, etc.) from GET method at a server and put it before response data f.e in php:

<?php header('content-type: application/json;');
$json=json_encode($result);
echo $_GET['callback'].'('.$json.')';
?>

回答1:

Issue is because url is getting cached in browser and the other time it will fetch from the cache.So I'd suggest you to add new dummy parameter inside you URL that will have current Date.now() so that every time you call service that will make URL unique doe to Date.now() component.

Code

$http.jsonp('http://www.where2play.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+
 e + '&dummy='+ Date.now()) //<--this will add new value everytime to make url unique