解释jQuery中向服务器发送请求的常见方法
在这篇文章中,我们将看到通过使用jQuery库向服务器发送请求的常用方法。jQuery是一个开源的JavaScript库,jQuery简化了HTML文档的遍历和操作、浏览器事件处理、DOM动画、Ajax交互的跨浏览器JavaScript开发。
向服务器发送请求的常见方法: jQuery有两个方法get()和post(),用于向服务器发送get请求和post请求。
- 第一个方法是get()方式,用于从服务器上检索数据。get()方法可能会返回缓存的数据。
 - post()方法也可以用来从服务器上获取数据。然而,post总是使用发送数据到服务器,而且Post方法从不缓存数据。
 
使用jQuery get()方法向服务器发送请求: $.get()方法从服务器加载数据。
语法:
$.get(url,callback);
参数:
- Url。所需的URL参数指定了你想请求的URL。
 - callback。可选的回调参数是在请求成功时要执行的函数的名称
 
例子1:在这个例子中,我们将制作一个data.txt文件。当你点击获取请求按钮时,这个文件将被返回。
data.txt:
GeeksforGeeks
index.html:
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <script type="text/javascript" 
            src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
    </script>
    <title>Get Request Example in JQuery</title>
    <script>
        (document).ready(function () {
            ('#Get-Method').click(function () {
                .get('data.txt', function (data, status) {
                    ('#output').append(data);
                    $('#response').append("Response: " + status);
  
                }, 'text');
            });
        });
    </script>
</head>
  
<body>
    <button id="Get-Method"> Get Request</button>
    <p id="output"></p>
    <p id="response"></p>
</body>
  
</html>
输出

获取方法输出
使用jQuery post()方法向服务器发送请求: post()方法从服务器加载数据或向服务器发送数据。
语法:
$(selector).post(url,data,callback ,dataType);
参数:
- Url。所需的URL参数指定了你想请求的URL。
 - data。数据参数数据被发送到服务器。
 - callback。如果请求成功,回调函数何时被执行。
 - dataType:数据类型是指数据的类型。
 
例子2:这个例子使用post()方法向服务器发送请求。
data.php:该文件将在你点击发布请求按钮时被调用。
<?php
    echo "GeeksforGeeks" ;
?>
index.html:
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <script type="text/javascript" 
            src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
    </script>
    <title>Get Request Example in JQuery</title>
</head>
  
<body>
    <h3>GeeksForGeeks</h3>
    <button id="Post-Method"> 
        Post Request Example
    </button><br><br>
    Response From Server:<h3 id="output"></h3>
    <script>
        (document).ready(function () {
            ("#Post-Method").click(function () {
                $.post('data.php', { name: "GFG" }, function (data, status) {
                    document.getElementById('output').innerHTML = data;
                });
            });
  
        });
    </script>
</body>
  
</html>
输出:

极客教程