2013-04-26 22 views
7

Newbie in Knockout, anche un progettista front-end, quindi ho bisogno di parole semplici.Recupero o invio di dati da un modulo utilizzando knockout.js

Ho un modulo che ho bisogno di inviare al database e poi recuperare dal database in seguito.

Si prega di spiegare in termini molto semplici come produrre un esempio funzionante per illustrare il salvataggio e la pubblicazione di un modulo?

Dal tutorial di knockout: http://knockoutjs.com/documentation/json-data.html Ho capito di ricevere e inviare dati JSON. Come vengono abbinati i dati JSON al modulo? Che cos'è la mappatura e c'è un plugin o un semplice esempio di come mappare i dati di JSON nel mio modulo? Fondamentalmente, come faccio a fare ciò che è commentato all'interno degli esempi di codice ad eliminazione diretta qui sotto?

recuperare i dati:

$.getJSON("/some/url", function(data) { 
    // Now use this data to update your view models, 
    // and Knockout will update your UI automatically 
}) 

di invio dati:

var data = /* Your data in JSON format - see below */; 
$.post("/some/url", data, function(returnedData) { 
    // This callback is executed if the post was successful  
}) 
+0

Pensare a leggere questo - http://knockoutjs.com/documentation/submit-binding.html - e questo - http://knockoutjs.com/documentation/value-binding.html - è il modo migliore. –

risposta

13

forma semplice

<form data-bind="submit: onSubmit"> 
    <input data-bind="value : firstName"/> 
    <input data-bind="value : lastName"/> 
    <input type="submit" text="Submit!"/> 
</form> 
Response: <span data-bind="text : response"></span> 

semplice modello vista

var viewModel = new function() 
{ 
    var self = this; 
    self.firstName = ko.observable("default first"); 
    self.lastName = ko.observable("default last"); 
    self.responseJSON = ko.observable(null); 
    self.onSubmit = function() 
    { 
     var data = JSON.stringify(
      { 
       first : self.firstName(), last : self.lastName()   
      }); // prepare request data 
     $.post("/echo/json", data, function(response) // sends 'post' request 
     { 
      // on success callback 
      self.responseJSON(response); 
     }) 
    } 
} 

ko.applyBindings(viewModel); 

JSFiddle DEMO

+0

@llya Cool budy – Developerzzz