jQuery 如何通过单击链接而不提交按钮来发出 AJAX 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10734749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:41:41 来源:igfitidea点击:
How Make AJAX REQUEST with clicking in the link not submit button
提问by choppermio
How could I make an AJAX REQUEST by clicking on a link instead of a submit button? I want once the link is clicked to POST data from input fields
如何通过单击链接而不是提交按钮来创建 AJAX 请求?我想一旦点击链接从输入字段发布数据
回答by Ankur Verma
$('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
});
});
回答by Vishal
Here's how AJAX works:
以下是 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);
});
});
回答by Vishal
With jQuery
使用 jQuery
$('#link-selector').on('click', function(event) {
event.preventDefault();
$.post('url', {$('form selector').serialize()}, function(json) {
// proccess results
}, 'json');
});
回答by cmilhench
You can user JQuery and the Form serialize functionality
您可以使用 JQuery 和 Form 序列化功能
$('#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
}
});
});