2017-08-02 97 views
4
$.ajax({ 
    type: 'POST', 
    url: '@Url.Action("SetDisplaySettings", "DisplaySettings")', 
    data:$('#Form1').serialize(), 
    success: function (result) { 
     $('#chkIsSystemDefault').prop('checked', false); 
     if(result=="2"){ 
      showAlertBox("Display Settings updated."); 
     } 
    } 
}); 

我需要再傳一個參數CountryId。我怎樣才能做到這一點?如何在ajax中傳遞更多參數?

+0

可能像'數據:{數據:$( '#Form1的')序列化(),countryId:CountryId}' –

回答

4

不喜歡它低於你當前的代碼(將數據添加到連載形式本身): -

data:$('#Form1').serialize()+ '&CountryId=' + CountryId, 

或者你可以使用serializeArray[docs]

var data = $('#myForm').serializeArray(); 
data.push({name: 'CountryId', value: CountryId}); 
+0

謝謝@Alive到死 –

+0

@DevTry高興幫助你的朋友:) :) –

2

你可以傳遞一個object作爲你的數據像這樣:

$.ajax({ 
     type: 'POST', 
     url: '@Url.Action("SetDisplaySettings", "DisplaySettings")', 
     data:{ 
      form : $('#Form1').serialize(), 
      other : ... 
     }, 
     success: function (result) { 
      $('#chkIsSystemDefault').prop('checked', false); 
      if(result=="2") 
      { 
       showAlertBox("Display Settings updated."); 
      } 
     } 
    }); 
0

這裏是僞代碼來幫助你理解你怎麼能在AJAX請求傳遞多個參數:

var paramsToSend = {}; 
paramsToSend['form'] = $('#myForm').serializeArray(); 
paramsToSend['CountryId'] = CountryId; 

$.ajax({ 
    ... 
    data: {params:JSON.stringify(paramsToSend)}, 
    ... 
}); 

在你的服務器端,可能是PHP,您可以:

$parameters = json_decode($_POST['params']); 

將它們轉換爲數組,並在$ _POST數組,你可以:

$_POST = (array) $parameters; 
0

相反的$(...).serialize()可以使用FormData對象:FormData on MDN。 做這樣的事情:

var data = new FormData(document.getElementById("#myForm")); 
data.append("CountryId", countryIdValue); 
//... in AJAX block: 
data: data, 
//...