Ajax-15:JqueryのAjax

注:Jqueryを使用する前に、必ず関連ライブラリを導入してください。

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Jqueryを使用してGETリクエストを送信する

$('button').eq(0).click(function() {
    
    
  $.get('http://localhost:8000/jquery-server',{
    
    a:20,b:30},function(data) {
    
    
      console.log(data);
  },'json')
});

Jqueryを使用してPOSTリクエストを送信します

$('button').eq(1).click(function() {
    
    
    $.post('http://localhost:8000/jquery-server',{
    
    a:20,b:30},function(data) {
    
    
        console.log(data);
    })
});

一般的なメソッドリクエストにはJqueryを使用します

// 通用型方法
$('button').eq(2).click(function () {
    
    
    $.ajax({
    
    
        url: 'http://localhost:8000/jquery-server',
        data: {
    
     a: 20, b: 100 },
        dataType: 'json',
        type: 'GET',
        success: function (data) {
    
    
            console.log(data);
        },
        // 超时时间
        timeout: 4000,
        error: function () {
    
    
            console.log("网络超时");
        },

        headers: {
    
    
            a: 666,
            b: 777
        }
    })
})
  • 上記の属性の多くはカスタマイズできます。
  • ヘッダーを設定する場合、サーバーには次のコードが必要です
response.setHeader('Access-Control-Allow-Headers', '*');

おすすめ

転載: blog.csdn.net/sinat_41696687/article/details/114747299