AJAX jQuery.load versus jQuery.get

前端 未结 4 798
深忆病人
深忆病人 2020-11-27 20:16

When should the load( url, data, callback ) method be used versus jQuery.get( url, data, callback, type ) when making AJAX calls with jQuery?

相关标签:
4条回答
  • 2020-11-27 20:38

    would only have to look at the jQuery code, as it is available for review. anyway all calls must reach the same method but respond in different ways depending on the need

    0 讨论(0)
  • 2020-11-27 21:00

    First of all those two functions are completely different. The 'load' function works with selectors and loads the result of AJAX call inside the selected group and the callback is to handle the "oncomplete" event of the call; while the $.get function is more general and the callback handles the success response of AJAX call where you are free to define any behavior you want. And you can find all this information just by looking at the documentation and specification of the jQuery framework.

    Here you can find a good documentation.

    0 讨论(0)
  • 2020-11-27 21:00

    @Artem's answer seems to be missing the fact that the load is a more generic function than get. According to the jQuery API docs, load uses get or post depending on the data. Quoting it here:

    Request Method

    The POST method is used if data is provided as an object; otherwise, GET is assumed.

    So for the purpose of getting partial HTML content from the server & inserting it into the DOM, load is a better method than the get method, as the developer does not need to worry about handling huge data & various intermediate steps that the load function does before fetching & before inserting the content.

    For instance, if you need to load partial content of a page, you could use the following expression: $('#result').load('ajax/test.html #container');

    This retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

    One thing to keep in mind is that, when you just need a GET request avoid providing an object to the data parameter & instead use the $.param method to get a serialized form of the request parameters.

    0 讨论(0)
  • 2020-11-27 21:05

    load injects the data directly into the DOM. If you don't need this behavior, use get.

    0 讨论(0)
提交回复
热议问题