2010-07-13 95 views

回答

3

我認爲代碼給你一個不好的味道的原因是因爲寫json作爲字符串是相當臭的。一個小小的改進就是創建一個真正的JSON對象,然後使用JSON.stringify(...)函數。

與JSON對象創建一個變量,這給你的語法在設計時檢查和運行時間

var customerInput = {"customerToAssignTo":$("#customerToAssignTo").val()}; 
var serializedCustomerInput = JSON.stringify(customerInput); 

,那麼你可以更換線

data: "{'customerToAssignTo':'" + $("#customerToAssignTo").val() + "'}" 

data: serializedCustomerInput 

您需要包含https://github.com/douglascrockford/JSON-js/blob/master/json2.js

更多信息:

http://www.json.org/js.html

http://msdn.microsoft.com/en-us/library/cc836459(VS.85).aspx - 這是在Windows腳本的上下文,但是給出了函數的一個很好的說明

1

正如我發佈這個,我發現了一種方法,但我真的不喜歡它。 這非常麻煩,需要構建自己的Json,這似乎不是一個好的解決方案。

var validated = $("#aspnetForm").validate(
    { 
     rules: 
     { 
      customersToReassign: 
      { 
       required: true 
      }, 
      customerToAssignTo: 
      { 
       required: true, 
       remote: 
       { 
        url: window.location + "/IsValidCustomer", 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        data: "{'customerToAssignTo':'" + $("#customerToAssignTo").val() + "'}" 
       } 
      } 
     },