4

如何通过单击链接而不是提交按钮来发出 AJAX 请求?我希望单击链接后从输入字段中发布数据

4

4 回答 4

12
$('selector').click(function(e){
  e.preventDefault();
  $.ajax({
       url: "<where to post>",
       type: "POST",//type of posting the data
       data: <what to post>,
       success: function (data) {
         //what to do in success
       },
       error: function(xhr, ajaxOptions, thrownError){
          //what to do in error
       },
       timeout : 15000//timeout of the ajax call
  });

});
于 2012-05-24T09:37:17.967 回答
3

以下是 AJAX 的工作原理:

$('#link_id').click(function(event){
   event.preventDefault(); // prevent default behavior of link click
   // now make an AJAX request to server_side_file.php by passing some data
   $.post('server_side_file.php', {parameter : some_value}, function(response){
      //now you've got `response` from server, play with it like
      alert(response);
   });
});
于 2012-05-24T09:47:02.197 回答
2

您可以使用 JQuery 和表单序列化功能

$('#A-id-selector').click(function() {
    $.ajax({
        type:'POST', 
        url: 'target.url', 
        data:$('#Form-id-selector').serialize(), 
        success: function(response) {
          // Any code to execute on a successful return
        }
    });
});
于 2012-05-24T09:40:17.980 回答
1

使用 jQuery

$('#link-selector').on('click', function(event) {
    event.preventDefault();
    $.post('url', {$('form selector').serialize()}, function(json) {
        // proccess results
    }, 'json');
});
于 2012-05-24T09:36:33.673 回答