用ajax传递链接的值

时间:2018-11-24 02:44:00

标签: jquery ajax

我的通知警报具有此代码。 如何在href链接中传递stdid值? 可能吗? 我没有设法使其正常工作,但我尝试了一些操作,但似乎没有任何效果...

$(document).ready(function() {

  $(document).on('click', '.notered<?= $a?>', function() {


    $.ajax({

      type: 'POST',
      url: 'ntupdate.php',
      data: {
        "stdid": <?= $note['id']?>
      },
      success: (
        alert('<?= $note['
          id ']?>')
      )
    });

  });
})
<a href="" name="stdid" value="<?= $note['id']?>" class="dropdown-item noti-container py-3 border-bottom border-bottom-blue-grey border-bottom-lighten-4 notered<?= $a?>">
  <i class="ft-bell info float-left d-block font-large-1 mt-1 mr-2"></i>
  <span class="noti-wrapper">
                                    <span class="noti-title line-height-1 d-block text-bold-400 info">שיבוץ חדש במערכת </span>
  <span class="noti-text"><?= $note['std_name']  ?></span>
  </span>
</a>

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery的.attr()函数从链接中获取所需的数据。 锚标记的HTML:

<a class='.myAnchor' href='#' value='shalom'>Shalom</a>

javascript:

$('.myAnchor').on('click', function(e){
    var value = $(this).attr('value');
});

现在您有了该值,可以根据需要将其传递到数据中

$('.myAnchor').on('click', function(e){
    var value = $(this).attr('value');
    $.ajax({
        type: 'POST',
        url: 'ntupdate.php',
        data: {'stdid': value},
        success:(
             alert(value);
    )                                                                                  
});

});

jQuery文档: http://api.jquery.com/attr/

从表单传递数据:(提供您自己的网址) HTML:

<form class='myForm'>

<a class='.myAnchor' href=# value='shalom'>Shalom</a>
<input type='hidden' name='stdid' class='.hiddenInput value='someValue' />

</form>

JS:

//make the anchor trigger the form submit and set the input value to be the correct value
$('.myAnchor').on('click', function(e) {
    $('.hiddenInput').val('$(this).attr('value'));
    $('.myForm').trigger('submit');
});

//on form submit do the ajax call 
$('.myForm').on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation();

    //this makes the form data into a JSON object for you to use
    var data = $(this).serialize();

    $.ajax({
        type: 'POST',
        url: url,
        data: data
    });

});