jQuery $.ajax() 和 $.get() 和 $.load() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3870086/
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 16:15:12  来源:igfitidea点击:

Difference between $.ajax() and $.get() and $.load()

jqueryajax

提问by Vaibhav Jain

What is the difference between $.ajax()and $.get()and $.load()?

是什么区别$.ajax(),并$.get()$.load()

Which is better to use and in what conditions?

在什么条件下使用哪个更好?

回答by Alexander Sagen

$.ajax()is the most configurable one, where you get fine grained control over HTTP headers and such. You're also able to get direct access to the XHR-object using this method. Slightly more fine-grained error-handling is also provided. Can therefore be more complicated and often unecessary, but sometimes very useful. You have to deal with the returned data yourself with a callback.

$.ajax()是最可配置的一种,您可以在其中对 HTTP 标头等进行细粒度控制。您还可以使用此方法直接访问 XHR 对象。还提供了更细粒度的错误处理。因此可能更复杂,通常是不必要的,但有时非常有用。您必须通过回调自己处理返回的数据。

$.get()is just a shorthand for $.ajax()but abstracts some of the configurations away, setting reasonable default values for what it hides from you. Returns the data to a callback. It only allows GET-requests so is accompanied by the $.post()function for similar abstraction, only for POST

$.get()只是一种简写,$.ajax()但抽象了一些配置,为其隐藏的内容设置了合理的默认值。将数据返回给回调。它只允许 GET 请求,因此伴随着$.post()类似抽象的函数,仅用于 POST

.load()is similar to $.get()but adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other, global, calls, as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...)

.load()类似于$.get()但增加了功能,允许您定义要在文档中插入返回数据的位置。因此,只有在调用只会导致 HTML 时才真正可用。它的调用方式与其他全局调用略有不同,因为它是一种绑定到特定 jQuery 包装的 DOM 元素的方法。因此,一个人会这样做:$('#divWantingContent').load(...)

It should be noted that all $.get(), $.post(), .load()are all just wrappers for $.ajax()as it's called internally.

应该注意的是,所有$.get(), $.post(),.load()都只是$.ajax()内部调用的包装器。

More details in the Ajax-documentation of jQuery: http://api.jquery.com/category/ajax/

jQuery 的 Ajax 文档中的更多详细信息:http: //api.jquery.com/category/ajax/

回答by Felix Kling

The methods provide different layers of abstraction.

这些方法提供了不同的抽象层。

  • $.ajax()gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get()executes an Ajax GETrequest. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load()will execute an Ajax GETrequest and will set the content of the selected returned data (which should be either text or HTML).

  • $.ajax()使您可以完全控制 Ajax 请求。如果其他方法不能满足您的需求,您应该使用它。

  • $.get()执行 AjaxGET请求。返回的数据(可以是任何数据)将传递给您的回调处理程序。

  • $(selector).load()将执行 AjaxGET请求并设置所选返回数据的内容(应该是文本或 HTML)。

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

这取决于您应该使用哪种方法的情况。如果您想做简单的事情,则无需费心$.ajax()

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax()or $.get().

例如$.load(),如果返回的数据将是需要进一步处理的 JSON,则您不会使用。在这里,您可以使用$.ajax()$.get()

回答by deceze

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

jQuery.ajax()

Description: Perform an asynchronous HTTP (Ajax) request.

jQuery.ajax()

描述:执行异步 HTTP (Ajax) 请求。

The full monty, lets you make any kind of Ajax request.

完整的 monty,让您可以发出任何类型的 Ajax 请求。



http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.get/

jQuery.get()

Description: Load data from the server using a HTTP GET request.

jQuery.get()

描述:使用 HTTP GET 请求从服务器加载数据。

Only lets you make HTTP GET requests, requires a little less configuration.

只允许你发出 HTTP GET 请求,需要的配置少一点。



http://api.jquery.com/load/

http://api.jquery.com/load/

.load()

Description: Load data from the server and place the returned HTML into the matched element.

.load()

描述:从服务器加载数据并将返回的 HTML 放入匹配的元素中。

Specialized to get data and inject it into an element.

专门用于获取数据并将其注入元素。

回答by Tim

Very basic but

非常基本但是

  • $.load(): Load a piece of html into a container DOM.
  • $.get(): Use this if you want to make a GETcall and play extensively with the response.
  • $.post(): Use this if you want to make a POSTcall and don't want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
  • $.load(): 将一段html加载到容器DOM中。
  • $.get():如果您想进行GET调用并广泛使用响应,请使用此选项。
  • $.post():如果您想进行POST调用并且不想将响应加载到某个容器 DOM,请使用此选项。
  • $.ajax():如果您需要在 XHR 失败时执行某些操作,或者您需要即时指定 ajax 选项(例如缓存:true),请使用此选项。

回答by pymen

Important note :jQuery.load()method can do not only GETbut also POSTrequests, if dataparameter is supplied (see: http://api.jquery.com/load/)

重要说明:如果提供了数据参数,jQuery.load()方法不仅可以执行GET请求,还可以执行POST请求(请参阅:http : //api.jquery.com/load/

dataType: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POSTmethod is used if data is provided as an object; otherwise, GETis assumed.

数据类型:PlainObject 或字符串 随请求发送到服务器的普通对象或字符串。

请求方法如果数据作为对象提供,则使用POST方法;否则,假定为GET

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

回答by Isaac Levi Felix Salinas

Everyone has it right. Functions .load, .get, and .post, are different ways of using the function .ajax.

每个人都说得对。函数.load.get、 和.post是使用函数的不同方式.ajax

Personally, I find the .ajax raw function very confusing, and prefer to use load, get, or post as I need it.

就个人而言,我发现 .ajax 原始函数非常令人困惑,并且更喜欢在需要时使用 load、get 或 post。

POST has the following structure:

POST 具有以下结构:

$.post(target, post_data, function(response) { });

GET has the following:

GET 具有以下内容:

$.get(target, post_data, function(response) { });

LOAD has the following:

负载有以下内容:

$(*selector*).load(target, post_data, function(response) { });

As you can see, there are little differences between them, because its the situationthat determines which one to use. Need to send the info to a file internally? Use .post (this would be most of the cases). Need to send the info in such a way that you could provide a link to the specific moment? Use .get. Both of them allow a callback where you can handle the response of the files.

如您所见,它们之间几乎没有区别,因为情况决定了使用哪个。需要在内部将信息发送到文件吗?使用 .post(这是大多数情况)。需要以可以提供特定时刻链接的方式发送信息吗?使用.get。它们都允许回调,您可以在其中处理文件的响应。

An important note is that .load acts in two different manners. If you only provide the url of the target document, it will actas a get (and I say act because I tested checking for $_POSTin the called PHP while using default .load behaviour and it detects $_POST, not $_GET; maybe it would be more precise to say it acts as .post without any arguments); however, as http://api.jquery.com/load/says, once you provide an array of arguments to the function, it will POST the information to the file. Whatever the case is, .load function will directly insert the information into a DOM element, which in MANY cases is very legible, and very direct; but still provides a callback if you want to do something more with the response. Additionally, .load allows you to extract a certain block of code from a file, giving you the possibility to save a catalog, for example, in a html file, and retrieve pieces of it (items) directly into DOM elements.

一个重要的注意事项是 .load 以两种不同的方式起作用。如果您只提供目标文档的 url,它将充当get(我说行为是因为我$_POST在使用默认 .load 行为时测试了在被调用的 PHP 中的检查,并且它检测到$_POST,而不是$_GET;也许它会更精确说它作为 .post 没有任何参数);但是,作为http://api.jquery.com/load/说,一旦你为函数提供了一个参数数组,它就会将信息发布到文件中。无论哪种情况,.load 函数都会直接将信息插入到 DOM 元素中,这在许多情况下非常清晰,而且非常直接;但如果你想对响应做更多的事情,仍然提供回调。此外,.load 允许您从文件中提取特定的代码块,使您可以将目录保存在例如 html 文件中,并将其中的部分(项目)直接检索到 DOM 元素中。

回答by jgauffin

$.get = $.ajax({type: 'GET'});

$.load()is a helper function which only can be invoked on elements.

$.load()是一个辅助函数,只能在元素上调用。

$.ajax()gives you most control. you can specify if you want to POST data, got more callbacks etc.

$.ajax()给你最大的控制权。您可以指定是否要发布数据、获得更多回调等。

回答by Subroto Biswas

Both are used to send some data and receive some response using that data.

两者都用于发送一些数据并使用该数据接收一些响应。

GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subrotoSo it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?

GET:获取存储在服务器中的信息。(即搜索、推文、个人信息)。如果要发送信息,则使用 get request 发送请求process.php?name=subroto所以它基本上是通过 url 发送信息。Url 不能处理超过 2036 个字符。所以对于博客文章,你记得这是不可能的吗?

POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.

POST: Post 和 GET 做同样的事情。用户注册、用户登录、大数据发送、博客文章。如果您需要发送安全信息,请使用 post 或大数据,因为它不通过 url。

AJAX: $.get()and $.post()contain features that are subsets of $.ajax(). It has more configuration.

AJAX$.get()$.post()包含作为$.ajax(). 它有更多的配置。

$.get ()method, which is a kind of shorthand for $.ajax(). When using $.get (), instead of passing in an object, you pass in arguments. At minimum, you'll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt)and a success callback.

$.get ()方法,这是 的一种简写$.ajax()。使用时$.get (),不是传入对象,而是传入参数。至少,您需要前两个参数,它们是要检索的文件的 URL(例如test.txt)和成功回调。

回答by Deepak Kumar

Everyone explained the topic very well. There is one more point i would like add about .load() method.

每个人都很好地解释了这个话题。关于 .load() 方法,我还想补充一点。

As per Load documentif you add suffixed selector in data url then it will not execute scripts in loading content.

根据加载文档,如果您在数据 url 中添加后缀选择器,则它不会在加载内容中执行脚本。

Working Plunker

工作Plunker

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html #content");
            })

On the other hand, after removing selector in url, scripts in new content will run. Try this example

另一方面,删除 url 中的选择器后,新内容中的脚本将运行。试试这个例子

after removing #content in url in index.html file

删除 index.html 文件中 url 中的 #content 后

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html");
            })

There is no such in-built feature provided by other methods in discussion.

讨论中的其他方法没有提供这种内置功能。