2015-07-19 51 views
1

PHP我具有被在客戶端側準備的KnockoutJS觀察的陣列:發帖KnockoutJS觀察的陣列,以通過Ajax

var invoices = function(invoiced_article_number,invoiced_article_name){ 
     this.invoicedArticleNumber = invoiced_article_number; 
     this.invoicedArticleName = invoiced_article_name; 
    }; 

陣列在頁面加載初始化:

this.selectedInvoices = ko.observableArray(); 

而且,在一個點擊一個按鈕某些元素被推入陣列:

self.selectedInvoices.push(new invoices(self.selectedArticle().articleNumber,self.selectedArticle().articleName)); 

我想通過這個可觀察數組t PHP通過Ajax post請求在MySQL中插入數據。我已經嘗試使用下面的代碼將其轉換爲Java腳本對象,但我一直在PHP中獲得空值。

var data = ko.toJS({"data":self.selectedInvoices}); 

Ajax請求:

$.ajax({ 
       url: "URL.php", 
       type: "post", 
       data: {invoiceData: data}, 
       cache: false, 
       success: function(returnedData) {} 
      }); 

PHP代碼:

$invoice_data = trim($_POST['invoiceData']); 

回答

2

您需要使用ko.toJSON以連載您的視圖模型到一些東西,可以發送到PHP。嘗試:

var data = ko.toJSON({"data":self.selectedInvoices}); 

這將發送一個字符串表示您的視圖模型的序列化狀態爲PHP。然後你可以使用PHP對它進行反序列化:

$invoice_data = json_decode(trim($_POST['invoiceData']));