javascript - Meteor 不接受 getJson 之外的 div 调用?

标签 javascript json ajax meteor

使用 Meteor.js 的经历非常奇特。我的代码是这样的:

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});
};

基本上,我使用 API 来获取 JSON 信息并将其放入我的 $('.location') div 中。这段代码有效。然而,这段代码却没有。

var tree = $('.location').text();
$('.repeat').text(tree);

具体来说,当我将此代码放在 getJSON 函数之外时,它不起作用。所以这样做...

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});


var tree = $('.location').text();
$('.repeat').text(tree);
};

以空的 div class="repeat" 结尾。但是,如果我像这样重新格式化...

Template.mytemplate.rendered = function(){

$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);

var tree = $('.location').text();
$('.repeat').text(tree);

});
};

然后我突然能够检索 div class="location" 的属性并将其放在我的 div class="repeat" 上。我想知道为什么会这样。

当 div 字符串包含 json 内容时,我不想在 getJSON 函数下严格调用它们。

最佳答案

用于将位置复制到重复元素中的 jQuery 代码将在初始化“.location”元素之前执行。

//rendered is old API.
Template.mytemplate.onRendered(function(){

$.getJSON('http://ip-api.com/json/?callback=?', function resultFn(lingo){
  //2. after some time this code will be executed
  $('.location').text(" " + lingo.zip + ", " + lingo.city);
});

  //1. code below will be executed first
  var tree = $('.location').text();
  $('.repeat').text(tree);
});
为什么? “getJSON”调用需要一些时间来执行,因为它通过网络上传一些外部数据。因此,您的回调“resultFn”将在一定延迟后执行。这就是为什么最后两行将首先执行的原因。

此外,使用 jquery 将数据放入模板并不是真正的 Meteor 方式。我能想到的解决方案是这样的:

<template name="myTemplate">
  <div class="location">
  {{location}}
  </div>

  <div class="repeat">
  {{location}}
  </div>
</template>

逻辑:

Template.myTemplate.onCreated(function(){
     this.location = new ReactiveVar(); //reactive-var package
     var self = this;
     $.getJSON('http://ip-api.com/json/?callback=?', function(lingo) {
        self.location.set(lingo.zip + ", " + lingo.city);
     });
});

Template.myTemplate.helpers({
  location: function(){
    return Template.instance().location.get();
  }
});

所以,现在您的数据以 react 方式呈现,您可以随时通过更改 react 变量的值来更改它。

关于javascript - Meteor 不接受 getJson 之外的 div 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951107/

相关文章:

javascript - 数组中的对象 : Unexpected String

java - XML 到 JSON 转换问题

php - 在 PHP 中格式化 JSON 格式的文本文件

php - 使用 AJAX 执行 PHP 脚本而不使用 POST/GET?

PHP 邮件总是给我 undefined index ,有帮助吗?

javascript - jquery 单击事件未在 Internet Explorer 上触发

Javascript/Excel ActiveX 对象。查找完全匹配

javascript - 使用 Parsley JS 添加从服务器返回的错误消息

java - 如何将@RequestBody 值传递给转发 Controller Spring MVC

java - Memcache 可序列化的 JSONObject?