如何设置简单的firebase ajax请求? [英] How do I setup simple firebase ajax request?
问题描述
我知道我可以使用set来点击Firebase,但我想使用AJAX,所以我尝试了下面的代码。当我在浏览器中加载test.html时,控制台会说 -
I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. When I load test.html in my browser, the console says -
XMLHttpRequest无法加载 https://jleiphonebook.firebaseio.com/json 。请求的资源上不存在Access-Control-Allow-Origin标头。因此不允许原点'null'访问。响应的HTTP状态代码为405.
XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
// text.html
//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规则
//firebase rules
{
"rules": {
".read": true,
".write": true
}
}
推荐答案
Firebase希望正文是一个JSON字符串,所以你'我需要对其进行字符串化:
Firebase expects the body to be a JSON string, so you'll need to stringify it:
$(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");
}
);
这篇关于如何设置简单的firebase ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!