2013-03-14 43 views
1

我正在讀一本關於asp.net MVC的書,並且我發現調用返回JSON的Action方法的不同方法:使用Ajax或getJSOn,在這兩種方法等同於: -Ajax和getJSON在調用返回JSON的操作方法時有什麼區別

$.ajax({ 
type: "GET", 
url: "http://localhost:11279/test/testcall", 
dataType: "json", 
success: function (result) { 
var message = result.Title + ": $" + result.CurrentPrice; 
$('#Result').html(message); 
}, 
error: function (XMLHttpRequest, textStatus, errorThrown) { 
alert("Error: " + errorThrown); 
} 
}); 

而且是的getJSON -

<script type="text/javascript"> 
$(function() { 
$.getJSON("http://localhost:11279/test/testcall", 
function (data) { 
$.each(data, function (key, val) { 
var str = val.Description; 
$('<li/>', { html: str }).appendTo($('#auctions')); 
}); 
}); 
}); 
</script> 

第二個問題

如果我想從控制器類調用上述操作方法或外部Web服務而不是使用javaScript,那麼應該使用哪種c-sharp方法?以及如何將返回的JSON從控制器類傳遞到風景。 BR

+1

「第二個問題」應該是第二個問題,不追加到這一個。 – SpaceBison 2013-03-14 10:06:27

回答

1

的getJSON - 方法允許通過使Ajax調用頁面獲取JSON數據。此方法只允許通過get方法傳遞參數發佈參數是不允許的。

Ajax() - 此方法提供比我們所見的所有其他方法更多的控制。您可以通過查看參數列表來找出差異

  • 提供對數據發送和響應數據的更多控制。
  • 允許處理呼叫期間發生的錯誤。
  • 如果對ajax頁面的調用成功,則允許處理數據。

答到2

您可以使用jquery + Ajax()功能來消耗它在HTML頁面中..

這裏是你的文章:Steps to Call WCF Service using jQuery

像這樣

function WCFJSON() { 
      var userid = "1"; 
      Type = "POST"; 
      Url = "Service.svc/GetUser"; 
      Data = '{"Id": "' + userid + '"}'; 
      ContentType = "application/json; charset=utf-8"; 
      DataType = "json"; varProcessData = true; 
      CallService(); 
     } 

//function to call WCF Service  
     function CallService() { 
      $.ajax({ 
       type: Type, //GET or POST or PUT or DELETE verb 
       url: Url, // Location of the service 
       data: Data, //Data sent to server 
       contentType: ContentType, // content type sent to server 
       dataType: DataType, //Expected data format from server 
       processdata: ProcessData, //True or False 
       success: function(msg) {//On Successfull service call 
        ServiceSucceeded(msg); 
       }, 
       error: ServiceFailed// When Service call fails 
      }); 
     } 
+0

感謝您的答覆,那麼你的意思是我可以編寫上述函數CallService(){在我的c-sharp控制器類中? – 2013-03-14 10:13:46

+0

@ johnG-檢查所有信息逐步解釋的鏈接 – 2013-03-14 10:45:47

相關問題