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

南楼画角 提交于 2019-11-27 14:30:10

问题


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?

Also, what is the difference in how they are actually sent?


回答1:


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)




回答2:


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.




回答3:


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.



回答4:


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



来源:https://stackoverflow.com/questions/1376369/get-vs-post-ajax-requests-when-and-how-to-use-either

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!