我知道我可以使用set来点击Firebase,但我想使用AJAX,所以我尝试了下面的代码。当我在浏览器中加载test.html时,控制台会说 -
XMLHttpRequest无法加载https://jleiphonebook.firebaseio.com/json。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许原点'null'访问。响应的HTTP状态代码为405。
// text.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Firebase Test</title>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
</head>
<body>
<div id="hi"></div>
<script src="https://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/json',
type: "POST",
data: param,
success: function () {
alert("success");
}
});
});
</script>
</body>
</html>
// firebase规则
{
"rules": {
".read": true,
".write": true
}
}
答案 0 :(得分:3)
Firebase希望正文为JSON字符串,因此您需要对其进行字符串化:
$(document).ready(function () {
var param = {lastName: "Doe", firstName: "John"};
$.ajax({
url: 'https://jleiphonebook.firebaseio.com/.json',
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("success");
},
error: function(error) {
alert("error: "+error);
}
});
});
顺便提一下:
$.post('https://jleiphonebook.firebaseio.com/.json',
JSON.stringify(param),
function () {
alert("success");
}
);