如何运行2个javascript代码以获得正确的结果

时间:2016-10-30 19:06:22

标签: javascript jquery angularjs asp.net-mvc

我正在构建一个MVC项目。我得到用户当前位置的城市并将其放在网页的右上角,这是第一个运行的javascript代码。第二个javascript代码运行以获取该城市的天气状况。但是当js运行以获得天气时,城市名称不是由第一个js设定的。

所以,我需要确保在运行第二个js之前,第一个js完成。我怎么能这样做?

这是我的js代码。

首先是jquery代码

$ sudo apt-get install ipython python-opencv python-scipy python-numpy python-setuptools python-pip

第二个代码是角度js

<script>
    function GetUsersInfo()
    {
        $.get("http://ipinfo.io", function (response) {
            $("#cityName").html(''+response.city);
            if ($("#cityName").html === "")
            {
                $("#cityName").html("İstanbul");
            }
        }, "jsonp");
    }
    GetUsersInfo();
</script>

3 个答案:

答案 0 :(得分:1)

在您的情况下,我会在同一个流程中发出两个请求,并使用async来管理它们。

使用异步,您可以使用waterfall方法执行此操作:

var async = require('async');

var app = angular.module("ZenHaberApp", []);
app.controller("WeatherController", function ($scope, $http) {

    async.waterfall([
      function (callback) {
        // Make the request to get the city, if jsonp needed check $http.jsop method (remember to use the $sce module to trust the source)
        // Assign the city to a $scope variable, which with angular simple add {{city}} to show to the user
        // Async takes callbacks with two params (error, result) so you could do callback(err, city)
      },
      function (city, callback) {
        $http.get('http://localhost:62747/api/getweatherbycityname/' + city).
        success(function (data, status, headers, config) {
            callback(null, data)
        }).
        error(function (data, status, headers, config) {
                        callback(true);
        });
      }
    ], function (err, result) {
        if (err) {
        // Handle error 
      } else {
        $scope.weathers = data.condition_temp;
      }
    });    
});

答案 1 :(得分:1)

几个选项:

  1. 使用事件,在加载数据后,您可以发送全局事件并在其他任何地方收听。 observer模式在jQuery中实现,因此您已经使用了jQuery,这很容易。 ($ .on和$ .trigger)

  2. 因为您使用的是jsonp,所以可以使用jsonp回调。 Wiki中的进一步解释:https://en.wikipedia.org/wiki/JSONP#Callback_name_manipulation_and_reflected_file_download_attack

  3. 显然使用了interval(setInterval并检查了value元素),虽然这不是一个好方法

  4. 在我看来,选项1是最好的方法。

    我已经考虑到代码是完全分开的,你不想把角度与第一部分结合起来。

答案 2 :(得分:0)

如果您使用的是Angular 2,则可以调用Lifecycle Hooks

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

(我不知道是否是Angular第一版特色)

在那里,您可以在视图或组件的生命周期中定义scrips,然后您可以在不同的生命周期钩子中设置该scrips。

我希望有所帮助。