AJAX请求使用的HTTP GET/POST方法

Which method HTTP GET/POST used by AJAX requests?

本文关键字:GET POST 方法 HTTP 请求 AJAX      更新时间:2023-09-26

AJAX请求使用的HTTP GET/POST方法?我们可以在进行Ajax调用时指定方法吗?

AJAX请求使用的HTTP GET/POST方法?

。遵循通常的规则来决定哪个是合适的。(例如,GET是可重复的,POST更改内容,等等)。如果您正在使用XHR,大多数浏览器将允许您使用任何HTTP方法,而不仅仅是GET和POST。

我们可以指定的方法,而使Ajax调用?

是的。好。通常。Ajax只是意味着"在不离开当前页面的情况下发出HTTP请求并读取响应";有很多不同的方法可以做到这一点。XHR允许指定方法,JSON-P不允许,向隐藏的iframe提交表单允许,向页面动态添加图像不允许,等等。

AJAX请求使用的HTTP GET/POST方法?

两者都使用,基于程序员。

我们可以指定的方法,而使Ajax调用?

是的,你可以。这取决于你发送ajax的方法

您可以两者都使用-取决于您想要做什么。GET用于检索没有副作用的数据。您还可以使用其他方法,例如DELETE和PUT。

可以同时使用GET或POST。这些是web浏览器支持的HTTP方法之一,您可以通过AJAX或传统方式使用它。

这段代码应该可以帮助您入门:

var params={
    type: "POST",   //you can make this GET
    url: "./ajax/addFriend.php",
    data: "friend="+friend,
    success: function(msg){
      alert('Friend added successfully');
    },
    error: function(){
      alert("There was an error processing your request. Please try again.");
    }
  };
  var result=$.ajax(params).responseText;

是的,您可以在调用时指定方法。例如,使用jquery,您可以使用调用方法类型参数:

"请求的类型("POST"或"GET"),默认为"GET"。注意:其他HTTP请求方法,如PUT和DELETE,也可以此处使用,但并非所有浏览器都支持。"

$.ajax({
   type: "GET",
   url: "test.js",
   dataType: "script"
 });
$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

AJAX调用可以使用GET或POST…你决定…

有几种方法可以做到这一点…使用XMLHttpRequest对象的纯JavaScript,或者使用AJAX框架(如jQuery)。

纯JavaScript示例

//Create an instance
req = new XMLHttpRequest();
//Use the open command to open the connection...note the username and password
//are used as needed and are not required
//open( Method, URL, Asynchronous, UserName, Password )
req.open('GET','/path/to/send/request',true);  //Could also use POST
//Set a callback to handle the request response
req.onreadystatechange = function() {
    //Common practice to check the ready state and handle it appropriately
    //ready state === 4 is for success
    if(req.readyState === 4) {
        //Do stuff...
    }
}
//Now make the request using the send call
//send( Data )
req.send(null);

XMLHttpRequest Object还有其他有用的事件和选项。还有一个API用于与响应交互。文档可以在这个链接中找到

现在使用AJAX框架也是可能的,并且可以使事情简单得多。jQuery是我个人偏爱的框架。

jQuery示例

//Here we use jQuery framework to make the call
//With jQuery, you set the options and supply a call back
$.ajax({
    type: "POST",                       //type GET/POST/ETC
    url: "some.php",                    //URL to send to
    data: "name=John&location=Boston",  //data you want to send
    success: function(msg){             //Callback when request is a success
        alert( "Data Saved: " + msg );
    }
});
//Could also do a 'GET' request
jQuery AJAX文档可以在这里找到

使用AJAX框架,如jQuery,将简化API调用,使其更易于阅读和编写更少的代码。缺点是您获得了库的开销(性能和控制空间大小)。

如果您计划在整个站点中使用该框架(用于AJAX调用和DOM操作),那么我会使用jQuery,但如果是用于一个或两个调用,则只使用XMLHttpRequest调用,因为开销将不值得。