如果它的内部jquery重复将无法工作

时间:2012-05-02 05:20:56

标签: javascript jquery

function stationMenu($ scope){

$.ajax({
    url: "/users/station_names_ajax",
    type: "POST",

    success: function(data){

        $scope.phones = [
            {"name": "Nexus S",
                "snippet": "Fast just got faster with Nexus S."},
            {"name": "Motorola XOOM™ with Wi-Fi",
                "snippet": "The Next, Next Generation tablet."},
            {"name": "MOTOROLA XOOM™",
                "snippet": "The Next, Next Generation tablet."}
        ];

        //console.log(Stations); 
    }
});

// $scope.phones = Stations;
// console.log(Stations);

}

好像我这样做

function stationMenu($scope){

    $scope.phones = [
        {"name": "Nexus S",
            "snippet": "Fast just got faster with Nexus S."},
        {"name": "Motorola XOOM™ with Wi-Fi",
            "snippet": "The Next, Next Generation tablet."},
        {"name": "MOTOROLA XOOM™",
            "snippet": "The Next, Next Generation tablet."}
    ];
}

它有效....如何让它在ajax中运行

2 个答案:

答案 0 :(得分:1)

function callService(){
    return  $.ajax({
    url: "/users/station_names_ajax",
    type: "POST",

    success: function(data){


        //console.log(Stations); 
    }
});
}
var $scope= {};

$.when(callService())
 .then(function(data){
           $scope.phones = [
                                   {"name": "Nexus S",
                                    "snippet": "Fast just got faster with Nexus S."},
                                   {"name": "Motorola XOOM™ with Wi-Fi",
                                    "snippet": "The Next, Next Generation tablet."},
                                   {"name": "MOTOROLA XOOM™",
                                    "snippet": "The Next, Next Generation tablet."}
                                 ];

 });

使用when,then构造来处理从服务器返回的数据。

答案 1 :(得分:0)

你再来一次..现在有很多问题。
首先我假设您放入$ scope.phones的值是从ajax请求返回的,并且不是硬编码的,否则硬编码值就没有意义了 默认情况下,jquery中的ajax请求是异步的 因此,您需要对返回的数据执行的所有操作都需要在success ajax request事件内完成 所以在你的样本中

function stationMenu($scope){

        $.ajax({
              url: "/users/station_names_ajax",
              type: "POST",

              success: function(data){


                  $scope.phones = [
                                   {"name": "Nexus S",
                                    "snippet": "Fast just got faster with Nexus S."},
                                   {"name": "Motorola XOOM™ with Wi-Fi",
                                    "snippet": "The Next, Next Generation tablet."},
                                   {"name": "MOTOROLA XOOM™",
                                    "snippet": "The Next, Next Generation tablet."}
                                 ];


                  //console.log(Stations);
//make use of anything returned and and $scope.phones here
              }
            });

//these lines wont work here
       // $scope.phones = Stations;
       // console.log(Stations);

    }