2013-04-15 25 views
8

我正在使用x-editable進行內聯編輯。當我通過ajax和x-editable更新值來獲得響應時,我發現覆蓋包含新的x-editable值的div非常困難。如何重寫x-editable ajax響應值?

例如,我的X-編輯鏈接看起來是這樣的:

<a href="#" id="freight">$100</a> 

輸入我的彈出窗口,X-編輯提供再輸入值300.00

當我做編輯我的編輯,我進行如下操作:

$('#freight').editable({ 
      validate: function(value) { 
       if($.trim(value) == '') return 'This value is required.'; 
      }, 
      type: 'text', 
      url: '{{ path('update_purchase_order_ajax') }}', 
      pk: {{ purchaseOrder.id }}, 
      title: 'Enter Freight Value', 
      ajaxOptions: { 
       dataType: 'json' 
      }, 
      success: function(response, newValue) { 
       // Update the purchase order amounts... 
       $('#freight').html('$' + newValue); 
      } 
     }); 

當x編輯完成後,顯示在頁面上的值現在爲300.00(不含$美元符號)。正如你可以在我的jQuery代碼中看到的,我試圖重寫x-editable在$('#freight')。html('$'+ newValue)中放置頁面的值。

由於某種原因,這是行不通的。我想要$ 300.00出現,而不是300.00。

+0

不應該把\ $。這對我有點困惑 – Lamis

回答

2

X編輯有一個選項「顯示:函數(值,響應){}」,它可以用於修改頁面上顯示的數據:

, 
display: function(value, response) { 
     $(this).text(response.new_value); 
     // new_value being the value that is returned via the json response... 
     // this value can either be modified here in the javascript or in the controller which set the value... 
}, 
10

你需要做的是防止什麼display方法覆蓋您的success方法。

display: function(value, response) { 
    return false; //disable this method 
}, 
success: function(response, newValue) { 
    $(this).html('$' + newValue); 
} 

在服務器端,你的JSON應該是這樣的,{newValue : <value>}

1

以下兩種情況

案例1:你想只顯示值不同

可以使用渲染事件

$('#action').on('render', function(e, editable) { 
    var colors = {0: "gray", 1: "green", 2: "blue", 3: "red"}; 
    $(this).css("color", colors[editable.value]); 
}); 

案例2:您希望將值設置爲在Ajax響應中返回的元素,而不是在客戶端設置的值。 uesr插入值「Hello」,但服務器將其轉換爲「hello」(小寫),然後執行以下操作

in ajax response set new value {"success":true,"pk":13,"value":"hello"}

使用下面的代碼

success:function(data, config) { 
    if(typeof(data) == 'object'){ 
     var api_id = data.pk; 
     var success = data.success; 
     if(success == true){ 
      return {newValue:data.value} 
     } 
    } 
} 

確保返回的對象與確切的名字NEWVALUE

3

只要您迴應的格式爲:

{"success":true,"pk":2311,"newValue":"somenewvalue"} 

你確保返回成功callba的響應ck:

success: function(response) { 
    var newValue = '$'+response.newValue; 
    response.newValue = newValue; 
    return response; 
} 

然後x-editable應該爲你更新該字段。請記住在響應中包含success,pknewValue鍵。

0
success: function(response, newValue) { 
    // Update the purchase order amounts... 
    $('#freight').editable('option', 'value', newValue); 
} 
+0

請提供你的代碼的解釋,所以OP可以從中學習。 – EBH