weixin_33709364 2016-04-13 07:55 采纳率: 0%
浏览 10

加载脚本异步?

EDIT: I want to save input data from my form into Firebase database

The input with id="field0" and button with onClick"submitPost()"

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

Cannot put the firebase.js into the head. So solved it like this. If I add the snippets one by one into the console it seems to work. But get an error when I load them all in the console at the same time.

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('');
}

Here is the above example: https://jsfiddle.net/hbaecklund/7mnns4dk/5/

Do I need to do async loading of the script in order to work? But below doesn't work?

$.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('');
    };    
  }
});
  • 写回答

1条回答 默认 最新

  • 零零乙 2016-04-13 08:03
    关注

    Try this, by using the load event of the script tag: https://jsfiddle.net/7mnns4dk/6/

    Basically just use:

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

    Also it works with jQuery as you wrote it, just move the submitPost function so that it is accessible by the button: https://jsfiddle.net/7mnns4dk/7/

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办