2010-09-01 35 views
1

我提出AJAX調用(ASP.NET 3.5),並試圖下拉ID傳遞到Ajax調用:的jquery從下拉菜單更改處理傳遞控制ID爲內方法

$('select.facility').change(function() 
{ 
     if ($(this).val() != 0) 
     { 
      var params = new Object(); 
      params.facilityId = $(this).val(); 

      $.ajax(
       { 
        type: "POST", 
        data: $.toJSON(params), 
        dataType: "json", 
        contentType: "application/json", 
        url: "SomeURL.asmx/SomeMethod", 
        success: function(response) 
        { 
         //this is where I need to get a hold of my dropdown, 
         // $(this) obviously doesn't work, using just to illustrate 
         $(this).closest('table').next('table') 
         .find('input.address').val(response.d.Address); 

        } 

     } 
}); 

是否有任何優雅的方式來做到這一點?

回答

2

您可以使用this,你只需要添加context option of $.ajax()所以this是有用的:

$('select.facility').change(function() { 
    if ($(this).val() == 0) return; 
    var params = { facilityId = $(this).val() }; 
    $.ajax({ 
     context: this,       //add this! 
     type: "POST", 
     data: $.toJSON(params), 
     dataType: "json", 
     contentType: "application/json", 
     url: "SomeURL.asmx/SomeMethod", 
     success: function(response) { 
     $(this).closest('table').next('table') 
       .find('input.address').val(response.d.Address); 
     } 
    }); 
}); 
+0

謝謝,這是最優雅的做法 順便說一句,如果你有多個參數要傳遞,你就不能使用這個'params'語法 – Victor 2010-09-01 17:01:47

+0

@Victor - 你可以,它看起來像這樣:'var params = {name1:'value1',name2:'value2'}',只需在對之間使用逗號:) – 2010-09-01 17:07:01

0

如果您不堅持使用AJAX,您可以簡單地將下拉菜單的AutoPostback屬性設置爲true,並在後面的代碼中處理更改後的事件。

+0

感謝您的答覆。其實我堅持AJAX的原因有很多。 – Victor 2010-09-01 16:30:34

1
... 
var parentContext = $(this); 
$.ajax(
{ 
    type: "POST", 
    data: $.toJSON(params), 
    dataType: "json", 
    contentType: "application/json", 
    url: "SomeURL.asmx/SomeMethod", 
    success: function(response) 
    { 
     //this is where I need to get a hold of my dropdown, 
     // $(this) obviously doesn't work, using just to illustrate 
     parentContext.closest('table').next('table') 
     .find('input.address').val(response.d.Address); 

    } 
    ...