jQuery 中 $.getJSON() 和 $.ajax() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1076013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:36:21  来源:igfitidea点击:

Difference Between $.getJSON() and $.ajax() in jQuery

asp.net-mvcjquery

提问by ChrisP

I am calling an ASP.NET MVC action

我正在调用 ASP.NET MVC 操作

public JsonResult GetPatient(string patientID)
{
...

from JavaScript using jQuery. The following call works

从 JavaScript 使用 jQuery。以下调用有效

$.getJSON(
'/Services/GetPatient',
{ patientID: "1" },
function(jsonData) {
  alert(jsonData);
});

whereas this one does not.

而这个没有。

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { patientID: "1" },
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});

Both reach the action method, but the patientID value is null w/ the $.ajax call. I'd like to use the $.ajax call for some of the advanced callbacks.

两者都到达了 action 方法,但是带有 $.ajax 调用的患者 ID 值为空。我想对一些高级回调使用 $.ajax 调用。

Any thoughts appreciated.

任何想法表示赞赏。

采纳答案by Dave Ward

Content-type

内容类型

You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.

您不需要在调用 MVC 控制器操作时指定该内容类型。只有在调用 ASP.NET AJAX“ScriptServices”和页面方法时才需要特殊的“application/json; charset=utf-8”内容类型。jQuery 的默认 contentType “application/x-www-form-urlencoded”适用于请求 MVC 控制器操作。

More about that content-type here: JSON HiHymaning and How ASP.NET AJAX 1.0 Avoids these Attacks

有关该内容类型的更多信息: JSON 劫持和 ASP.NET AJAX 1.0 如何避免这些攻击

Data

数据

The data iscorrect as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.

数据正确的,因为你有它。通过向 jQuery 传递一个 JSON 对象,正如您所拥有的,它将在 POST 数据中序列化为 PatientID=1。这种标准形式是 MVC 期望参数的方式。

You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.

当您使用 ASP.NET AJAX 服务时,您只需要将参数括在引号中,例如 "{ 'patientID' : 1 }"。他们期望解析出表示 JSON 对象的单个字符串,而不是 POST 数据中的各个变量。

JSON

JSON

It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.

在这种特定情况下这不是问题,但养成在 JSON 对象中引用任何字符串键或值的习惯是个好主意。如果您无意中将 JavaScript 保留关键字用作对象中的键或值,而没有引用它,您将遇到混淆调试的问题。

Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.

相反,您不必引用数字或布尔值。直接在对象中使用它们总是安全的。

So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:

因此,假设您确实想要 POST 而不是 GET,您的 $.ajax() 调用可能如下所示:

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { 'patientID' : 1 },
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});

回答by redsquare

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

.getJson 只是 .ajax 的包装器,但它提供了一个更简单的方法签名,因为一些设置是默认的,例如 dataType 为 json,type 为 get 等

N.B .load, .get and .post are also simple wrappers around the .ajax method.

注意 .load、.get 和 .post 也是 .ajax 方法的简单包装器。

回答by cutts

Replace

代替

data: { patientID: "1" },

with

data: "{ 'patientID': '1' }",

Further reading: 3 mistakes to avoid when using jQuery with ASP.NET

进一步阅读:在 ASP.NET 中使用 jQuery 时要避免的 3 个错误

回答by Vivek

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

jquery 的一些功能如 $.ajax, $.get, $.post, $.getScript, $.getJSON 有很多混淆,他们之间有什么区别,哪个最好,哪个最快,哪个使用和何时使用下面是对它们的描述,以使它们清晰并摆脱这种类型的混淆。

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

$.getJSON() 函数是 Ajax 函数的简写(内部使用 $.get() 与数据类型脚本),相当于下面的表达式,使用一些有限的条件,如请求类型为 GET,数据类型为 json。

Read More .. jquery-post-vs-get-vs-ajax

阅读更多 .. jquery-post-vs-get-vs-ajax

回答by kgiannakakis

The only difference I see is that getJSON performs a GET request instead of a POST.

我看到的唯一区别是 getJSON 执行 GET 请求而不是 POST。

回答by Mathias F

contentType: 'application/json; charset=utf-8'

Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.

不好。至少它对我不起作用。其他语法没问题。您提供的参数格式正确。

回答by Siva Varma Bayyavarapu

with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

使用 $.getJSON()) 没有任何错误回调,只有您可以跟踪成功回调,并且不支持像 beforeSend、statusCode、mimeType 等标准设置,如果您希望它使用 $.ajax()。