GET vs. POST ajax requests: When and how to use either?

后端 未结 4 495
野的像风
野的像风 2020-12-15 05:01

What are the strengths of GET over POST and vice versa when creating an ajax request? How do I know which I should use at any given time? Is it a security-minded decision?

相关标签:
4条回答
  • 2020-12-15 05:21

    GETs should be used for idempotent operations, that is operations that can be safely repeated more than once without changing anything. Browsers will cache GET requests (for normal and AJAX requests)

    POSTs should be generally be used for non-idenpotent operations, like saving something. Although you can use them for other operations if you want.

    Data for GETs is sent over the URL query string. Data for POSTs is sent separately. Some browsers have a maximum URL length (I think Internet Explorer is 2048 characters), and if the query string becomes too long you'll get an error.

    0 讨论(0)
  • 2020-12-15 05:21

    You should use GET and POST requests in AJAX calls just as you would use GET and POST requests in normal calls. Basic rule of thumb:

    Will the request modify anything in your Model?

    • YES: The request will modify (add/update/delete) data from your data store, or in some other way change the state of the server (cause creation of a file, for example). Use POST.
    • NO: The request will not affect the state of anything (database, file system, sessions, ...) on the server, but merely retrieve information. Use GET.
    0 讨论(0)
  • 2020-12-15 05:37

    POST requests are requests that you do not want to accidentally happen. GET requests are requests you are OK with happening by a user pointing a browser to via a URL.

    GET requests can be repeated quite simply since their data is based in the URL itself.

    You should think about AJAX requests like you think about regular form requests (and their GET and POST)

    0 讨论(0)
  • 2020-12-15 05:37

    The Yahoo! Mail team found that when using XMLHttpRequest, POST is implemented in the browsers as a two-step process: sending the headers first, then sending data. So it's best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies). The maximum URL length in IE is 2K, so if you send more than 2K data you might not be able to use GET.

    http://developer.yahoo.com/performance/rules.html#ajax_get

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