BackboneJS Backbone.emulateHTTP


如果使用不支援Backbone預設REST/ HTTP方式的傳統網路伺服器,那麼你可以選擇開啟Backbone.emulateHTTP。 設定這個選項為true,將偽造PUT, PATCH ,DELETE和HTTP POST請求,設定使用真實的方法在X-HTTP-方法- 覆蓋頭部。 如果emulateJSON開啟,方法將被傳遞作為additional _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>

輸出

讓我們進行以下步驟來看看上面的程式碼工作:

  • 儲存以上的程式碼到emulatehttp.html檔案

  • 在瀏覽器開啟這個HTML檔案。