2016-01-22 47 views
2

我正在使用AJAX調用來顯示基於用C#編寫的某些邏輯的成功或失敗的信息。我現在需要從服務器返回附加數據並顯示它。我需要的數據包含在employersagencies變量中。如何將return Json聲明中的數據與success一起退回?在C#中通過AJAX從服務器返回數據

$.ajax({ 
    url: rootpath + "/clients/hasDuplicateTaxId", 
    type: "GET", 
    success: function (data) { 
     if (data.success) { 
      // success 
     } 
     else { 
      // fail 
     } 
    }, 
    error: function (response) { 
     var error = response; 
    } 
}); 
if (taxIdExists) 
{ 
    var employers = _employerRepository.GetByTaxId(taxId).ToList(); 
    var agencies = _employerRepository.GetByTaxId(taxId).Select(e => e.GeneralAgency).ToArray(); 
    return Json(new { success = true }, JsonRequestBehavior.AllowGet); 
} 

return Json(new { success = false, error = "Error" }, JsonRequestBehavior.AllowGet); 
+2

將'employers'和'agencies'變量添加到您提供給Json響應的匿名類型。然後可以訪問它們在JavaScript的'data'變量中公開的屬性/對象/數組。你不可能給你更具體的東西,因爲你沒有向我們展示這些類實際上是什麼樣的。 –

+2

看看你用C#代碼中的'error'成員做了什麼?對其他人也做同樣的事情。 –

+0

那會怎樣?像這樣? return Json(new {success = true,employers = employer,agencies = agencies},JsonRequestBehavior.AllowGet); – noclist

回答

1

您需要的employersagencies變量添加到您提供給Json匿名類型,像這樣:

if (taxIdExists) 
{ 
    var employers = _employerRepository.GetByTaxId(taxId).ToList(); 
    var agencies = _employerRepository.GetByTaxId(taxId).Select(e => e.GeneralAgency).ToArray(); 
    return Json(new { success = true, employers, agencies }, JsonRequestBehavior.AllowGet); 
} 

從那裏,你可以訪問存儲在這些屬性的陣列success$.ajax處理者電話:

success: function (data) { 
    if (data.success) { 
     console.log(data.employers); 
     console.log(data.agencies); 
    } 
    else { 
     // fail 
    } 
}, 

它們將是數組,因此您需要遍歷它們以提取所需的信息。

+0

在將這些變量添加到我的匿名類型後,我放入了我的Ajax請求的錯誤設置。 – noclist

+0

你得到的錯誤是什麼?您可以設置斷點來查找它,或者在控制檯中檢查請求的狀態。 –

+0

我設置了一個斷點,它碰到'error:function(response)'的內部。我怎麼知道錯誤是什麼? – noclist