首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能访问在较高作用域中创建的变量

问为什么我不能访问在较高作用域中创建的变量
EN

Stack Overflow用户
提问于 2015-06-27 04:13:44
回答 2查看 55关注 0票数 1

出于某些原因,我正在努力使用这段js代码。我不能访问ajax函数中的变量。我试图通过将"formatted“变量放在ajax函数之上来解决这个问题,但我无法从内部访问它。我该如何解决这个问题?

代码语言:javascript
复制
angular.module('ireg')
.controller("compoundSearchController", function(){
    var vm = this;
    vm.searchText = "Enter your search here...";
    vm.compounds = getJSON();

    function getJSON(){
        var formatted = "initial";  

        console.log(formatted); // equals initial

        $.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
            formatted = jQuery.parseJSON( result );
            console.log(formatted); //equals the correct object
        }})

        console.log(formatted); // equals initial
        return formatted;
    }

    console.log(vm.compounds); // equals initial

});
EN

回答 2

Stack Overflow用户

发布于 2015-06-27 04:18:01

AJAX调用的异步行为是造成实际行为与预期行为不同的原因。

将您的代码更新为

代码语言:javascript
复制
var formatted = "initial";  

$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
    formatted = jQuery.parseJSON( result );
    vm.compounds = formatted;
}})
票数 1
EN

Stack Overflow用户

发布于 2015-06-27 04:18:04

因为它们本质上是asynchronous,所以在它的success之外无法获得ajax调用的响应。您需要使用它们的回调来获得类似于success的调用,或者您也可以使用.then函数,该函数在ajax调用得到解决时得到调用。

笔记

不要将jQuery ajax和AngularJS混用,这会扰乱digest周期,您需要手动强制执行,一定要用$http替换ajax

更新

下面是angular版本的$.ajax

代码语言:javascript
复制
    $http.get("http://localhost:8080/ireg/app/php/returnAllCompounds.php")
    .success(function(result){
        formatted = jQuery.parseJSON( result );
        console.log(formatted); //equals the correct object
    }});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31081394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档