我知道我可以使用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无法加载 jleiphonebook.firebaseio/json 。请求的资源上不存在Access-Control-Allow-Origin标头。因此不允许原点'null'访问。响应的HTTP状态代码为405.
XMLHttpRequest cannot load jleiphonebook.firebaseio/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='cdn.firebase/js/client/2.2.1/firebase.js'></script> </head> <body> <div id="hi"></div> <script src="code.jquery/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script> <script> $(document).ready(function () { var param = {lastName: "Doe", firstName: "John"}; $.ajax({ url: 'jleiphonebook.firebaseio/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: 'jleiphonebook.firebaseio/.json', type: "POST", data: JSON.stringify(param), success: function () { alert("success"); }, error: function(error) { alert("error: "+error); } }); });顺便提一下:
$.post('jleiphonebook.firebaseio/.json', JSON.stringify(param), function () { alert("success"); } );更多推荐
如何设置简单的firebase ajax请求?
发布评论