BackboneJS-Sync 啟用 Backbone.emulateHTTP



說明

如果您使用的不支援 Backbone 的預設 REST/HTTP 方法的舊版 Web 伺服器,則可能選擇啟用 Backbone.emulateHTTP。將此選項設定為 true 將偽裝帶有 HTTP POST 請求的 PUT、PATCH 和 DELETE 請求,並將 X-HTTP-Method-Override 標頭設定為真正的方法。如果 emulateJSON 也處於啟用狀態,則真正的方法將作為其他 _method 引數傳遞。

語法

Backbone.emulateHTTP = true

示例

<!DOCTYPE html>
   <head>
      <title>Sync Example</title>
      <script src = "https://code.jquery.com/jquery-2.1.3.min.js" 
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" 
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" 
         type = "text/javascript"></script>
   </head>
   
   <body>
      <script type = "text/javascript">
         //If web server that doesn't support Backbone's REST/HTTP approach, 
         //then turn on 'Backbone.emulateHTTP'
         Backbone.emulateHTTP = true;
         
         //If web server can't handle requests encoded as application/json, 
         //then set the 'Backbone.emulateJSON' to true
         Backbone.emulateJSON = true;
         
         //The sync() method reads and fetch the model data
         Backbone.sync = function(method, model) {
            document.write(method + ": " + JSON.stringify(model));
            model.set('id', 1);   //Set the model with id as '1'
         };
         
         //'Player' is a model name and contains the values to be displayed 
         //when you save the model
         var Player = new Backbone.Model({
            fname:"Sachin",
            lname:"Tendulkar"
         });
         
         //The 'save()' method saves data of the model by delegating to sync() method
         Player.save();
         
         //Update the model with a value
         Player.save({country: "india"});
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟來檢視上面的程式碼如何工作:-

  • 將以上程式碼儲存到 backbone-emulateHTTP.htm 檔案中

  • 在瀏覽器中開啟此 HTML 檔案。

backbonejs_sync.htm
廣告
© . All rights reserved.