2015-01-12 63 views
0

所有:如何使用返回回調對象從快車在angularJS

[UPDATE] I figure it out, it turns out that:

 $http({ 
      url: "http://localhost:3000/users", 
      method: "JSONP", 
      params: { 
       callback:"JSON_CALLBACK", // need to be this name 

       q: $scope.qs 
      } 
     }) 
     .success(function(data){ 
      console.log("return data length:",data.length); 
      if(data.length>0){ 
       $scope.cdata = data; 
      } 
     }) 

======================== ================================== 我是ExpressJS和AngularJS的新手,現在,我嘗試着使用Express來構建REST JSONP服務來提供數據。

當我像前臺試角:

  $scope.qs = 0; 

      $http({ 
       url: "http://localhost:3000/users", 
       method: "JSONP", 
       params: { 
        callback:"dataservice", 
        q: $scope.qs 
       } 
      }) 
      .success(function(err, data){ 
       console.log("return data length:",data.length); 
       if(data.length>0){ 
        $scope.cdata = data; 
       } 
      }) 
      .error(function(data, err){ 
       console.log(data, err); 
      }); 
     }; 

在服務器端Annd我用:

/* GET users listing. */ 
router.get('/', function(req, res) { 

    var jsonp = req.query.callback; 
    var start = parseInt(req.query.q); 
    var retdata = []; 


    if(!isNaN(start)){ 
     retdata = cdata.slice(start); 
    } 
    if(jsonp){ 
     console.log("I return as JSONP"); 
     res.jsonp(retdata); 
    }else { 
     console.log("I return as JSON"); 
     res.json(retdata); 
    } 
}); 

從Chrome中的控制檯,我可以看到返回JSONP響應是這樣的:

/**/ typeof dataservice === 'function' && dataservice([{"Name":"Island Trading","City":"Cowes","Country":"UK"},{"Name":"Königlich Essen","City":"Brandenburg","Country":"Germany"},{"Name":"Laughing Bacchus Wine Cellars","City":"Vancouver","Country":"Canada"},{"Name":"Magazzini Alimentari Riuniti","City":"Bergamo","Country":"Italy"},{"Name":"North/South","City":"London","Country":"UK"},{"Name":"Paris spécialités","City":"Paris","Country":"France"},{"Name":"Rattlesnake Canyon Grocery","City":"Albuquerque","Country":"USA"},{"Name":"Simons bistro","City":"København","Country":"Denmark"},{"Name":"The Big Cheese","City":"Portland","Country":"USA"},{"Name":"Vaffeljernet","City":"Århus","Country":"Denmark"},{"Name":"Wolski Zajazd","City":"Warszawa","Country":"Poland"}]); 

但是Angular不能在.successs中使用它,但會觸發.error處理程序。

我不知道有人能幫助我嗎?如何使用返回響應

感謝

回答

0

試試這個,你要發送的回調,這樣是你必須調用來檢索數據:

function userCallback(data) { 
    console.log("return data length:",data.length); 
    if(data.length>0){ 
     $scope.cdata = data; 
    } 
} 

$http({ 
    url: "http://localhost:3000/users", 
    method: "JSONP", 
    params: { 
     callback: userCallback, 
     q: $scope.qs 
    } 
}).then(userCallback); 
+0

對不起,沒有奏效。錯誤:未捕獲的ReferenceError:未定義functionuserCallbackdataconsole – Kuan

+0

NVM,我自己弄明白了,事實證明回調名稱必須是JSON_CALLBACK – Kuan

相關問題