简体   繁体   English

如何设置简单的firebase ajax请求?

[英]How do I setup simple firebase ajax request?

I know I can use set to hit Firebase, but I want to use AJAX instead so I tried the below code. 我知道我可以使用set来命中Firebase,但我想使用AJAX,所以我尝试了下面的代码。 When I load test.html in my browser, the console says - 当我在浏览器中加载test.html时,控制台会说 -

XMLHttpRequest cannot load https://jleiphonebook.firebaseio.com/json . XMLHttpRequest无法加载https://jleiphonebook.firebaseio.com/json No 'Access-Control-Allow-Origin' header is present on the requested resource. 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access. 因此不允许原点'null'访问。 The response had HTTP status code 405. 响应具有HTTP状态代码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 rules // firebase规则

{
    "rules": {
        ".read": true,
        ".write": true
    }
}

Firebase expects the body to be a JSON string, so you'll need to stringify it: 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);
     }
   });
 });

This will accomplish the same by the way: 这将通过以下方式实现相同的目的:

$.post('https://jleiphonebook.firebaseio.com/.json',
  JSON.stringify(param),
  function () {
    alert("success");
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM