[英]How to pass parameter from a link to jquery method
當用戶單擊鏈接時,我需要觸發JQuery方法,並調用位於/Project/Send/SendMethod
的Web服務。 當我單擊send
鏈接時,該方法被觸發,我知道這一點,因為正在顯示警報。 但是問題是如何調用網絡服務。 如果它是POST
方法,那會很好。
<a href='' id='2' class='send'> Send </a>
jQuery方法
$(function () {
$('.send').click(function () {
alert(this.id);
});
});
使用$.ajax()
方法並指定url和類似jQuery Ajax的選項
$(function() {
$('.send').click(function (e) {
e.prevenDefault();
$.ajax({
url: "Project/Send/SendMethod",
type: "POST",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
}
});
});
});
使用jQuery $.post
:
$(function () {
$('.send').click(function () {
alert(this.id);
$.post(url, {'id':this.id}, function (response) {
//do the result oriented activities
});
});
});
您可以在jQuery中使用$.ajax()
API。 而且,您必須防止DefaultDefault鏈接中的默認行為。 否則,您將更改頁面而不發送ajax requset。
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id },
success:function(data) {
alert(data);
}
});
});
如果您使用的是jQuery 1.8+,則自jQuery 1.8開始不贊成使用“成功”回調。 您應該使用“完成” http://api.jquery.com/deferred.done/
$('.send').click(function (event) {
event.preventDefault();
$.ajax( {
url:"Project/Send/SendMethod",
type: "POST",
data: { "id": this.id }
}).done(function( data) {
alert(data);
});
});
我會使用jQuery的ajax()
功能(並定期這樣做)。
下面的示例假定您將獲得JSON格式的響應。 如果您要返回完整的HTML頁面,則可以更改此設置。有關更多信息,請訪問http://api.jquery.com/jQuery.ajax/ 。
$(function () {
$('.send').click(function (e) {
e.stopPropagation();
e.preventDefault();
var thisId = $(this).attr('id');
alert(thisId);
var hostAndPort = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port; // current page and protocol (http or https)
var requestUrl = hostAndPort + "/Project/Send/SendMethod/";
var str_address = requestUrl + 'id?=' + thisId;
$.ajax({
url: str_address,
contentType: 'application/json',
dataType: 'JSON',
type: 'POST',
success: function (response) {
console.log(response);
// do something...
},
error: function (e) {
// handle error
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.