Ajax和Ajax之间的区别是什么?调用返回JSON的操作方法时

What are the differences between Ajax & getJSON when calling an action method that return JSON

本文关键字:Ajax 返回 JSON 调用 操作方法 是什么 之间 区别      更新时间:2023-09-26

我正在读一本关于asp.net MVC的书,我发现调用返回JSON的Action方法的不同方法:,要么使用Ajax,要么使用getJSOn,所以这两个方法相当于:-

$.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

getJson方法允许通过对页面进行ajax调用来获取json数据。此方法只允许通过get方法传递参数,不允许发送参数。

Ajax ()-这个方法提供了比我们看到的所有其他方法更多的控制。您可以通过检查参数

的列表来找出差异。
  • 对数据发送和响应数据提供更多控制。
  • 允许处理呼叫过程中发生的错误。
  • 如果ajax页面调用成功,允许处理数据。

回答2

你可以使用jquery + Ajax()函数在你的html页面中使用它。

这里有一篇文章:使用jQuery调用WCF服务的步骤。

像这样的

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
             });
         }