You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在指定JavaScript函数中添加GET请求调用add.php?id=1?

如何在点击事件中添加向add.php的GET请求?

嘿,你要把发送GET请求的代码直接放在点击事件的回调函数内部,也就是$(this).on('click', function(e){ ... })这个函数块里,具体位置可以根据你的需求放在弹窗提示的前后,下面给你两种常见的实现方式:

方式一:带请求结果处理的版本(推荐)

如果想确保请求成功后再显示成功提示,或者需要处理请求失败的情况,可以用这个版本:

$('.js-addcart-b1').each(function(){ 
  var nameProduct = $(this).parent().parent().find('.js-name-b1').html(); 
  $(this).on('click', function(e){ 
    e.preventDefault(); 
    // 发送GET请求到add.php,携带id=1参数
    $.get('add.php', { id: 1 }, function(response) {
      // 请求成功后的回调,可以在这里处理返回的结果
      console.log('请求返回内容:', response);
      // 成功后弹出提示
      swal(nameProduct, "is added to cart !", "success"); 
    }).fail(function() {
      // 请求失败时的处理,比如提示错误
      swal('Oh no!', 'Failed to add item to cart', 'error');
    });
  }); 
});

方式二:简化版(不处理请求结果)

如果只是简单发送请求,不需要关心返回结果,可以直接写一行简化的代码:

$('.js-addcart-b1').each(function(){ 
  var nameProduct = $(this).parent().parent().find('.js-name-b1').html(); 
  $(this).on('click', function(e){ 
    e.preventDefault(); 
    // 直接发送GET请求
    $.get('add.php?id=1');
    // 弹出成功提示
    swal(nameProduct, "is added to cart !", "success"); 
  }); 
});

为什么放在这里?

因为点击事件的回调函数是用户点击按钮时才会触发的逻辑,只有把请求代码写在这里,才能保证每次点击按钮时都自动发送GET请求到add.php?id=1~

内容的提问来源于stack exchange,提问作者Milkasoprano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:09:25