【问题标题】:Access an element when the "Submit" button is clicked to get the values单击“提交”按钮以获取值时访问元素
【发布时间】:2016-04-02 16:02:59
【问题描述】:

所以这是来自https://developer.forecast.io/docs/v2的一个很好的例子

我想做和尝试的是:

我有一个简单的网页,我想在其中显示当前预测和扩展预测。

这是我的 Index.html

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html lang="en" class="no-js" ng-app="myApp">
    <head>
        <title>Weather Forecaster</title>
        <meta charset="UTF-8">
        <!-- favicon -->
        <link rel="shortcut icon" href="images/Oxygen-Icons.org-Oxygen-Status-weather-clear.ico" />
        <!-- END favicon -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="css/style.css" rel="stylesheet" type="text/css"/>
        <link href="css/jquery.jdigiclock.css" rel="stylesheet" type="text/css" />
        <link href="css/wx-custom.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="js/jquery-1.12.2.js"></script>
    </head>
    <body ng-controller="wxController as ctrlWx">
        <div class="container">
            <div class="row">
                <div class="col-10">
                    <div id="my-div" ng-model="myiFrame">
                        <iframe src="http://www.latlong.net/convert-address-to-lat-long.html" id="my-iframe" scrolling="no"></iframe>
                    </div>
                    <div id="plugin_container" class="forecast-panel">
                        <h1>Here's Today's Weather</h1>
                        <div class="fc forecast-panel1">
                            <p class="dayTitle">Day 1</p>
                        </div>
                        <div class="spacer"></div>
                        <div class="fc forecast-panel2">
                            <p class="dayTitle">Day 2</p>
                        </div>
                        <div class="spacer"></div>
                        <div class="fc forecast-panel3">
                            <p class="dayTitle">Day 3</p>
                        </div>
                        <div class="spacer"></div>
                        <div class="fc forecast-panel4">
                            <p class="dayTitle">Day 4</p>
                        </div>
                        <div class="spacer"></div>
                        <div class="fc forecast-panel5">
                            <p class="dayTitle">Day 5</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="js/angular/angular.min.js" type="text/javascript"></script>
        <script src="js/angular/app.js" type="text/javascript"></script>
        <script src="js/angular/controller.js" type="text/javascript"></script>
        <script src="js/angular/services.js" type="text/javascript"></script>
        <script src="js/angular/ang-custom.js" type="text/javascript"></script>
    </body>
</html>

注意“IFRAME”.... src 是这样的:http://www.latlong.net/convert-address-to-lat-long.html

现在,如果你去那里,这很酷,你可以输入任何地址来获取该地址的 LAT LON:

这是一个屏幕截图,其中包含来自 DC...白宫的 LAT LON 示例。

好的,现在,我的代码使用带有简单控制器和服务的 Angular...

这里:

应用程序:

/* global angular */
// Code goes here
var myApp;
myApp = angular.module("myApp", []);
myApp.config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist(['self', '**']);
});
console.log("Host name is: " + document.location.hostname);
//if (document.location.hostname === "localhost") {
//    myApp.constant('URL', '/WeatherForecaster/js/json/');
//} else if (document.location.hostname === "omnimanger.co/wx" || "www.omnimanager.co/wx") {
//    myApp.constant('URL', '/js/json/');
//} else {
//    myApp.constant('URL', '/wx/js/json/');
//}
myApp.constant("URL", {
   //Default LAT/LON for CONCRETE 
   apiKey: "3bb0f0fe93c92922f0b42f9eabda48d0/",
   lat: "48.530031",
   lon: ",-121.879460",
   country: "us",
   uri: "https://api.forecast.io/forecast/"
}).config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});;

myApp.constant("wx", {
    data: {
        latitude: 0,
        longitude: 0,
        currently: {},
        minutely: {
            summary: "",
            icon: "",
            data: []
        },
        hourly: {
            summary: "",
            icon: "",
            data: []
        },
        daily: {
            summary: "",
            icon: "",
            data: []
        },
        flags: {
            sources: [],
            "lamp-stations": [],
            "isd-stations": [],
            "madis-stations": [],
            units: ""
        }
    }
});

控制器:

'use strict';
myApp.controller('wxController', function (wxDataService) {

    var ctrlWx = this;
    //Listen for the Submit (FIND) button on the iFrame

    ctrlWx.content = {};
    console.log("LAT/LON: ", ctrlWx.latlon);
    ctrlWx.fetchWx = function () {
        //General Data
        wxDataService.getWxData().then(function (result) {
            ctrlWx.content = result;
            console.log("All Data: ", result);
        });
    };
    ctrlWx.fetchWx();

});

服务:

myApp.factory('wxDataService', function ($http, URL) {

    console.log("URL", URL);

        //DEFAULT Headers for KEY and AUTH TOKEN
    var headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': ['GET', 'POST'],
        'Access-Control-Allow-Headers': 'Content-Type',
        'Content-Type': 'application/json'
    };
    var myURL = {
        data: {
            header: headers,
            uri: URL.uri + URL.apiKey + URL.lat + URL.lon
        }
    };

    var getWxData = function () {
        return $http.get(myURL)
                .success(function (data) {
                    console.log("SUCCESS!");
                    console.log("The Weather Data is here: " + data);
                    return data;
                })
                .error(function (e) {
                    console.log("He\'s dead Jim!<br>", e);
                    return e;
                });
    };
    return {
        getWxData: getWxData
    };
});

我正在努力实现的解决方案:

当用户输入地址并单击“查找”按钮时,会生成 LAT LON,我想在 IFRAME 中捕获该 LAT LON。

这是我想要做的,但我知道我需要制定一个指令,将“CLICK”或“SUBMIT”事件绑定到 FIND 按钮。我下面的不是那个;还没有。

var latlon = {};
$(function () {
    $('#my-iframe').load(function () {

        $(this).contents().find("#latlongform, #gadres").live('blur', function (e) {
            latlon = {
                mylat: $("input[name='lat']").val(),
                mylon: $("input[name='lon']").val()
            };
            if (e) {
                console.log("Err: ", e);
                return e;
            }
        });
    });
});

给予:

FORM 和 LAT LON 如下:

    <div class="row">
        <div class="col-8 graybox">
            <form id="latlongform">
                <label for="gadres">Address</label>
                <input id="gadres" type="text" class="width70" placeholder="Type address here to get lat long" required="">
                <button title="Find lat long coordinates" class="button">Find</button><br>
                <small>Write city name with country code for better results.</small>
            </form>
            <div class="row">
                <div class="col-6 m2">
                    <label for="lat">Latitude</label>
                    <input type="text" name="lat" id="lat" placeholder="lat coordinate">
                </div>
                <div class="col-6 m2">
                    <label for="lng">Longitude</label>
                    <input type="text" name="lng" id="lng" placeholder="long coordinate">
                </div>
            </div>
        </div>
    </div>

问题:

如何获取 LAT LON,“在”用户单击“查找”后,然后启动我的 Angular 服务以将 CALL 注入到获取天气数据的 URL 中......如所述。这是天气数据 JSON 对象。它使用一个 API KEY,我的 API KEY 每天限制使用 1000 次。

如果您想查看天气 API 上的结果,您需要获取免费 API_KEY....它每天提供 1000 次点击...

谢谢大家,我希望你能做到这一切,这是一个有效的问题。

【问题讨论】:

  • 由于同源策略,您无法在跨域 iframe 中访问。另请注意,live() 已被弃用多年。此外,尝试在客户端请求上设置 CORS 访问控制标头也没有好处。它们必须由服务器在响应中设置
  • Live() - 是的,我打错了...原谅我。那么绝对没有办法获取这些数据呢?如果没有,我将只是拥有自己的表格,或者您是否知道另一种方法来执行该示例正在执行的操作?谢谢查理...感谢您的热心帮助。
  • 使用 AJAX 确实从您自己的表单中获取天气 API 的数据,这是 API 的使用方式。
  • 对,使用自己的表单。可以通过任何服务进行地理编码
  • 我是这么想的,但我想找到一种“酷”的方式来整合已经存在的东西。不用担心,查理。我可以为您和佛朗哥的两个答案“竖起大拇指”吗?对不起这个愚蠢的问题。先生们,请原谅我。

标签: javascript jquery html angularjs api


【解决方案1】:

使用 JSONP 访问 Forecast.io API

forecast.io 网站不支持 GET 操作的 CORS(跨源资源共享),但它支持 JSONP。

修改后的代码

var url = myURL.data.uri;
var jsonpURL = url+"?callback=JSON_CALLBACK";

var getWxData = function () {
    return $http.jsonp(jsonpURL)
        .then(function (response) {
            console.log("SUCCESS!");
            console.log(response.data);
            //return to chain data
            return response.data;
        })
        .catch(function (e) {
            console.log("He\'s dead Jim!");
            console.log(e);
            //throw to chain rejection
            throw e;
        });
};

样本结果

LAT: 48.530031
LOG: -121.87946
TIMEZONE: America/Los_Angeles
SUMMARY: Partly Cloudy
TEMP: 56.02

DEMO on JSFiddle

请注意,我将 .success.error 方法分别更改为 .then.catch。那些旧方法是 deprecatedignore 返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2020-12-03
    • 2020-12-25
    • 2019-08-22
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多