当我想发布一个变量但有 1 个 js 时,ajax post 的解决方案是什么

What is a solution for ajax post when I want to post a variable but have 1 js?

本文关键字:js ajax post 是什么 解决方案 布一个 变量      更新时间:2023-09-26

在我的页面中,我有以下代码,每个add-to-favor-后跟一个唯一的hash来区分我的多个结果。

<a class="btn btn-default btn-sm m-t-10 add-to-favor-'.$active[hash].'">
    <i class="text-danger fa fa-heart"></i>
</a>

问题是我不知道如何为我的问题提供一个通用的解决方案。我想将active[hash]传递给 ajax 帖子。我应该使用数据属性吗?如果是,如何?

$(function(){
    $('body').on('click', '.add-to-favor', function (){  
        $.ajax({
            cache: false,
            type: 'POST',
            url: ,
            data: ,
            success: function(data) {
                $('#show_the_favor').html(data);
            }
        });
    });
});

是的,你应该使用data-*属性。

将数据属性指定为 data-some-name="value" 。要获得该值,请使用.data('some-name')

<a data-hash="<?= $active['hash']; ?>" data-target="#show_the_favor" class="add-to-favor"></a>
$(document).ready(function () {
    $(document).on('click', '.add-to-favor', function () {
        var el = $(this);
        $.ajax({
            cache: false,
            type: 'POST',
            url: 'someUrl',
            data: {hash: el.data('hash')},
            success: function(data) {
                $(el.data('target')).html(data);
            }
        });
    });
}); 

是的,使用自定义属性。对于<a>元素,添加类add-to-favor但不要将哈希追加到该类。然后,添加另一个属性,data-hash="' . $active[hash] . '"

<a class="btn btn-default btn-sm m-t-10 add-to-favor" data-hash="' . $active[hash] . '">
    <i class="text-danger fa fa-heart"></i>
</a>

.JS:

$(function() {
  $('body').on('click', '.add-to-favor', function() {
    var hash = $(this).attr('data-hash');
    $.ajax({
      cache: false,
      type: 'POST',
      url: "script.php", // Enter the AJAX script URL
      data: {
          hash: hash
      },
      success: function(data) {
        $('#show_the_favor').html(data);
        // If you want to show the hash inside #show_the_favor, replace `data` above with `hash`
      }
    });
  });
});

你可以使用这个:

$('body').on('click', '[class*="add-to-favor"]', function (){
    var hash = $(this).attr('class').match(/add-to-favor-([^ ]+)/)[1];
    $.ajax({
      cache: false,
      type: 'POST',
      url: SomeUrl,
      data: {hash:hash},
      success: function(data) {
        $('#show_the_favor').html(data);
      }
   });
});

或者简单地使用数据属性:

<a class="btn btn-default btn-sm m-t-10" data-hash="'.$active[hash].'">
    <i class="text-danger fa fa-heart"></i>
</a>

并使用 $(this).data('hash') 获取哈希

你为什么不简单地制作自己的Javascript函数来做到这一点呢?

.HTML:

<a class="btn btn-default btn-sm m-t-10" onclick="add_to_favor('.$active[hash].');">
    <i class="text-danger fa fa-heart"></i>
</a>

Javascript/JQuery:

<script type="text/javascript">
function add_to_favor(hash){
  alert("pass it to your ajax: "+hash);
  $.ajax({
      cache: false,
      type: 'POST',
      url: ,
      data: ,
      success: function(data) {
          $('#show_the_favor').html(data);
      }
  });
}
</script>