【问题标题】:Load script async?异步加载脚本?
【发布时间】:2016-04-13 16:03:01
【问题描述】:

编辑:我想将表单中的输入数据保存到 Firebase 数据库中

id="field0" 的输入和onClick"submitPost()" 的按钮

<form>
<input id="field0" name="ePost" type="text" value="">
<button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>

无法将 firebase.js 放入头部。所以就这样解决了。如果我将 sn-ps 一个一个添加到控制台中,它似乎可以工作。但是当我同时将它们全部加载到控制台时会出错。

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "https://cdn.firebase.com/v0/firebase.js";
document.head.appendChild(script);

var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
});

function submitPost(e) {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
var name = $('#field0').val();
myDataRef.push({name: name});
$('#field0').val('');
}

这是上面的例子:https://jsfiddle.net/hbaecklund/7mnns4dk/5/

我需要异步加载脚本才能工作吗?但是下面不起作用?

$.ajax({
  url: 'https://cdn.firebase.com/v0/firebase.js',
  dataType: 'script',
  cache: true,
  success: function() {  
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
    myDataRef.on('child_added', function(snapshot) {
    var post = snapshot.val();
    });
    function submitPost(e) {
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
    var name = $('#field0').val();
    myDataRef.push({name: name});
    $('#field0').val('');
    };    
  }
});

【问题讨论】:

  • 你可以使用requirejs
  • 问题是您正在提交表单。您应该避免它并使用相关方法将数据发送到 Firebase。但是,为什么不能只在 head 中包含 firebase 脚本?

标签: javascript jquery ajax asynchronous


【解决方案1】:

试试这个,通过使用脚本标签的加载事件:https://jsfiddle.net/7mnns4dk/6/

基本上只使用:

script.load = function() {
  // enter code that needs the script to be loaded here
}

它也适用于您编写的 jQuery,只需移动 submitPost 函数以便可以通过按钮访问它:https://jsfiddle.net/7mnns4dk/7/

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 2016-07-09
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多