Javascript 如何使用$http的结果创建一个变量?

Javascript 如何使用$http的结果创建一个变量?,javascript,angularjs,json,Javascript,Angularjs,Json,我正试图通过以下行从http调用中获取json对象 var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc"); 当我记录它的时候 console.log(u); 我没有得到json的回报 Object { $$state: Object, success: $http/promise.success(), error: $http/promise.error() 如何

我正试图通过以下行从http调用中获取json对象

var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
当我记录它的时候

    console.log(u);
我没有得到json的回报

 Object { $$state: Object, success: $http/promise.success(), error: $http/promise.error()

如何使其作为json字符串返回?如果有必要的话,我会在工厂里使用它。谢谢。

$http.get
不会返回API发送的值。它只返回
HttpPromise
的对象。要获取该值,需要调用
u
上的
then
函数

var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");

u.then(function(response){
       var yourVar = response.data;
       console.log(yourVar);
    });

有关更多信息,请参见将http请求分配给变量不会导致服务调用。你需要尽快打电话

var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
$scope.ResponeData = null;
u.then(function(response){
    // Your response will be available here only
    $scope.ResponeData = response;
});

您可以找到有关承诺和web服务调用的更多详细信息。

当您执行HTTP请求时,该请求不会立即完成,而是异步完成。因此,当请求被发出时,您会得到一种令牌(承诺),您可以在请求“悬而未决”时跟踪它

此承诺是您在键入以下内容时记录的对象:

var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
console.log(u);
为了“跟踪”这一承诺,您可以通过使用
然后
错误
成功
最后
函数为其提供一些类似于事件处理程序的函数

下面是发生的情况:

// Start the request and get a promise that an answer will eventually come.
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");

// The request is handled asynchronously, so all we have now is the promise that
// at some time there will be a result.
console.log(u);

// Assign 'event handlers' to the promise
u.then(function(result) {
    // This 'event handler' function is called when the async process completes
    // successfully. You can now use the data as you please
    doFancyStuffWithResultData(result.data);
}, function(error) {
    // This 'event handler' function is called when the async process has an error
    console.error('Ohnoz, things went wrong', error);
});

请注意,我将“事件处理程序”放在引号中,因为它有助于将函数视为类似的-“事件处理程序”,但有一些区别。请查看文档,了解承诺是什么以及承诺如何工作的更多信息。

我能否在方法之外提供承诺?您可以为此将响应分配给范围变量或全局变量。我是JavaScript新手,全局变量与静态变量相同吗?如何将它分配给这样的变量,以便在代码中的任何地方都可以访问它?全局变量是一种静态变量。主要区别在于全局变量的可访问性与代码相关,而不是与时间相关。全局变量实际上在整个程序中都是可用的。由于您使用的是angular JS,我建议您使用scope变量。作用域变量的生命周期延伸到整个控制器。您可以在这里找到有关局部、全局和静态变量的更多信息。