我在firebase上有一個簡單的數據庫,基本上我試圖創建一個代碼來在這個數據庫上插入記錄。我想插入這樣的記錄:如何使用不同的ID在Firebase數據庫中插入項目?
id | lat | lng
01 | -55 | -10
02 | -44 | -20
每個「行」是一個地方(經度和緯度)的新紀錄。
我創建了火力這個例子:
我怎麼能記錄插入到這個「表」正確???因爲當我創建了下面的代碼來實現它,我打的按鈕,它在該表上創建一個不同的ID(我是新來的火力地堡,我沒有得到這個尚未):
下面是完整的代碼:
<form action="" id="newActivity">
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
<input id="saveForm" name="saveForm" type="submit" value="New Activity">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.3.2/firebase.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
//alert("This function is working!");
//alert(place.name);
// alert(place.address_components[0].long_name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script>
$(function(){
var rootRef = new Firebase("https://xxxx.firebaseio.com/").ref();
var placesRef = rootRef.child('places');
/**
* Data object to be written to Firebase.
*/
var data = []
$('#newActivity').submit(function(event){
var $form = $(this);
console.log("submit to Firebase");
//make the submit disabled
//$form.find("#saveForm").prop('disabled', true);
//get the actual values that we will send to firebase
var cityLatToSend = $('#cityLat').val();
console.log(cityLatToSend);
var cityLngToSend = $('#cityLng').val();
console.log(cityLngToSend);
//take the values from the form, and put them in an object
var newActivity = {
"lat": cityLatToSend,
"lng": cityLngToSend,
}
//put the new object into the data array
data.push(newActivity);
console.log(data);
//send the new data to Firebase
var newPlaceRef = rootRef.push();
newPlaceRef.set(data);
//rootRef.push(data);
return false;
})
})
</script>
非常感謝好友。我修改了代碼。但是當它創建一個新的「地點」時,它會使用這個自動生成的ID創建。不可能創建一個basica數字自動遞增ID? – Reif
這些密鑰保證是唯一的,稱爲推送ID。 –