简体   繁体   English

在流星助手中发出ajax请求

[英]making ajax request in meteor helpers

How can i wait until the ajax request finishes when returning data to a meteor helpers method. 在将数据返回到meteor helpers方法时,我怎么能等到ajax请求完成。

For example, 例如,

Template.item.helpers({

        itemName:function () {
            var user = Meteor.user();

            $.when(reallyLongAjaxRequest()).done(function (a1) {
               //tried using jquery when
                return "Item Name should have this because it waited";
            });

            return " Doesnt wait at all";
        }
    });

I have a reallyLongAjaxRequest() running and i would like it to finish before continuing on with my itemName helper. 我有一个reallyLongAjaxRequest()运行,我想在继续我的itemName帮助之前完成它。 The log statement to console always shows undefined but that's because the ajax request hasn't finished. 控制台的日志语句始终显示未定义,但这是因为ajax请求尚未完成。 I tried using the jquery when with no luck. 我没有运气时尝试使用jquery。 Any ideas 有任何想法吗

Edit: 编辑:

I should mention that i am inside the helper function for a reason. 我应该提一下,我在辅助函数中是有原因的。 I need the item 'id' being rendered so that i can run the ajax request with that paramater. 我需要呈现项目'id',以便我可以使用该参数运行ajax请求。 Using reactive sessions would be perfect but i don't know of a way to get currently rendering items outside of the helpers method definition? 使用被动会话将是完美的,但我不知道如何获得当前渲染项目在助手方法定义之外?

An unnamed collection is one where null is passed for the name. 未命名的集合是为名称传递null集合。 It is an in-memory data structure, not saved to the database. 它是内存中的数据结构,不保存到数据库中。 ( http://docs.meteor.com/#meteor_collection ) http://docs.meteor.com/#meteor_collection

OK, given a Meteor collection called "items" and wanting to do an ajax request for each item based on the item _id, and then being able to reference the ajax result in a template, this is what I'd do: 好的,给定一个名为“items”的Meteor集合,并希望根据项目_id对每个项目执行ajax请求,然后能够在模板中引用ajax结果,这就是我要做的:

(roughly) (大致)

var Items = new Meteor.Collection('items');
var Results = new Meteor.Collection(null);

Items.find().observeChanges({
  added: function (id) {
    $.get(url, {id: id}, function (data) {
      if (Results.findOne(id))
        Results.update(id, {$set: {result: data}});
      else
        Results.insert({_id: id, result: data});
    });
  }
});

Template.item.itemName = function (id) {
  var doc = Results.findOne(id);
  if (doc)
    return doc.result;
  else
    return "";
};

inside your html you'll need to pass in the id to the helper: 在您的HTML中,您需要将id传递给帮助者:

{{itemName _id}}

Is there no way to just timeout for a few seconds when defining the helper so that my ajax request finishes without immediately returning. 在定义帮助程序时,没有办法只是暂停几秒钟,以便我的ajax请求完成而不立即返回。

No, with reactive programming things happen immediately, but you update when you have new stuff. 不,随着反应式编程事情立即发生,但是当你有新东西时你会更新。

Make your ajax request separately, and when it completes, have it store the result in a Session variable. 单独制作ajax请求,完成后,将结果存储在Session变量中。 Then have your template helper return the value of the Session variable. 然后让模板助手返回Session变量的值。 Roughly... 大致...

$.get(url, function (data) {
  Session.set('result', data);
});

Template.item.itemName = function () {
  return Session.get('result');
};

Session is a reactive data source, so your template will automatically updated when the result of the ajax call comes in. (Naturally you can choose to call the Session variable anything you like, I just used "result" as an example). Session是一个被动数据源,因此当ajax调用的结果进入时,你的模板会自动更新。(当然你可以选择调用你想要的Session变量,我只是以“结果”为例)。

This works and tested in MeteorJS > 1.3.x 这在MeteorJS> 1.3.x中工作和测试

Add the http package from the console meteor add http 从控制台meteor add http添加http包

Example POST call with data elements being sent to server and with custom headers. 示例POST调用,将数据元素发送到服务器并使用自定义标头。

HTTP.call('POST', tokenUri, {
    data: {
        "type": 'authorization_code',
        //"client_id": clientId,
        "code": code,
        "redirect_uri" : redirectUri,

    },
    headers: {
        "Access-Control-Allow-Origin" : "*",
        "Access-Control-Allow-Credentials" : "true",
        "Access-Control-Allow-Methods" : "GET,HEAD,OPTIONS,POST,PUT",
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
    }
},function(error, response) {
    if ( error ) {
        console.log( error );
    } else {
        console.log( response );
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM