我使用Polymer1.0根据用户的位置使用iron-ajax
发出API请求。
在app.js中,我有以下块。
app.addEventListener('dom-change', function() {
console.log('Our app is ready to rock!');
var working = Polymer.dom(document).querySelector('#refresh-button');
var locationToast = Polymer.dom(document).querySelector('#toast');
var sightingsAjax = Polymer.dom(document).querySelector('iron-ajax#sightings');
var hotspotsAjax = Polymer.dom(document).querySelector('iron-ajax#hotspots');
function getLocation() {
working.setAttribute('class', 'spin');
function success(position) {
app.initialPosition = [position.coords.latitude,position.coords.longitude];
console.log(app.initialPosition);
app.apiRecent = 'http://ebird.org/ws1.1/data/obs/geo/recent?fmt=json&back=2' +
'&lat=' + app.initialPosition[0] + '&lng=' + app.initialPosition[1];
console.log(app.apiRecent);
app.apiHotspots = 'http://ebird.org/ws1.1/ref/hotspot/geo?dist=20&back=2&fmt=json' +
'&lat=' + app.initialPosition[0] + '&lng=' + app.initialPosition[1];
console.log(app.apiHotspots);
locationToast.text = 'Location acquired!';
locationToast.show();
working.removeAttribute('class');
sightingsAjax.url = app.apiRecent;
hotspotsAjax.url = app.apiHotspots;
}
function error() {
working.removeAttribute('class');
working.setAttribute('icon', 'error');
locationToast.text = 'Unable to determine location.' +
'Please check your settings and try again.';
locationToast.duration = 0;
locationToast.show();
}
navigator.geolocation.getCurrentPosition(success,error,{enableHighAccuracy: true});
}
getLocation();
app.refreshLocation = function() {
console.log('Refreshing user location...');
getLocation();
};
});
在我的index.html文件中,我有一个带有空url属性的iron元素。url是根据用户的位置坐标创建和添加的。
<section data-route="sightings">
<template is="dom-bind">
<iron-ajax
id="sightings"
auto
url=""
handle-as="json"
last-response="{{response}}"></iron-ajax>
<iron-list>
<template is="dom-repeat" items="{{response}}">
<div class="row">
<h4 class="title">[[item.comName]]</h4>
<div class="latin">[[item.sciName]]</div>
<div class="loc">Last spotted at <span>[[item.locName]]</span></div>
<div class="time">[[item.obsDt]]</div>
</div>
</template>
</iron-list>
</template>
</section>
这在Chrome和Opera (闪烁浏览器)中工作得很好,但在Safari和Firefox (都是最新版本,还没有在IE中测试)中失败。结果是一个空的iron-list
,因此基本上浏览器无法在受影响的浏览器中请求/返回API数据。
Safari给了我这个错误:TypeError: Attempted to assign to readonly property. success app.js:63
火狐说:TypeError: sightingsAjax is undefined
值得注意的是,地理位置、界面、路由和祝酒词在所有浏览器中都能正常工作。另外,手动设置iron-ajax
url属性也很好。在Firefox和Safari中,似乎失败的只是url属性的动态设置。
发布于 2016-01-21 11:18:53
回答我自己的问题。我可以直接在success()
回调中操作url属性,而不是将所选的元素存储在它们自己的变量中。
Polymer.dom(document).querySelector('#sightings iron-ajax').url = app.apiRecent;
Polymer.dom(document).querySelector('#hotspots iron-ajax').url = app.apiHotspots;
https://stackoverflow.com/questions/34929840
复制