所以我發送一個ajax請求到我的控制器進行處理。 但是,當我console.log消息在我的ajax做功能它顯示了兩個結果。在MVC控制器中處理時獲取重複動作
從的console.log結果是:
{"result_code":1,"result_message":"Contact tags deleted","result_output":"json"}
{"result_code":1,"result_message":"Contact tags added","result_output":"json"}
這是AJAX請求:
$('.travelSwitch').click(function() {
//send ajax request
$.ajax({
method: "POST",
url: "@Url.Action("ProcessPreferences", "ManagePreferences")",
data: {
//Applies to camping category
categoryTag: "Travel",
//send user email for processing
userEmailAddr: "@userEmailAddr",
//send remove flag for processing
removeTag: ($('#field_22Travel:checked').length) ? false : true
}
})
.done(function (msg) {
console.log(msg);
})
});
然後在我的控制器,用於處理Ajax請求的功能:
[HttpPost]
public ActionResult ProcessPreferences(string categoryTag, string userEmailAddr, bool removeTag)
{
string applyToTag = "TOPIC: " + categoryTag;
string emailAddr = userEmailAddr;
bool removeFlag = removeTag;
var acs = new Acs("api_key", "api_url");
Dictionary<string, string> getParameters = new Dictionary<string, string>();
if (removeFlag == false) {
//get parameters
getParameters.Add("api_action", "contact_tag_add");
getParameters.Add("api_output", "json");
}
else
{
//get parameters
getParameters.Add("api_action", "contact_tag_remove");
getParameters.Add("api_output", "json");
}
//post parameters
Dictionary<string, string> postParameters = new Dictionary<string, string>
{
{ "email", emailAddr },
{ "tags", applyToTag }
};
var response = acs.SendRequest("POST", getParameters, postParameters);
return Content(response);
}
因此,當處理ajax請求時,它會向活動的活動api發送一個請求。然後添加或刪除標籤,而不管複選框是否被選中。
注 開關是在這個實現:https://www.w3schools.com/howto/howto_css_switch.asp
初始Ajax請求的頁面加載發送到開關設定爲開或關:
$.ajax({
method: "POST",
url: "@Url.Action("InitPreferences", "ManagePreferences")",
data: {
userEmailAddr: "@userEmailAddr",
apiCallInit: true
}
})
.done(function (msg) {
//loop through tags
for (i in msg.tags) {
//console.log(msg.tags[i]);
(msg.tags[i] == "TOPIC: Camping") ? $("#field_22Camping").attr("checked", true) : "";
(msg.tags[i] == "TOPIC: Hiking") ? $("#field_22Hiking").attr("checked", true) : "";
(msg.tags[i] == "TOPIC: Travel") ? $("#field_22Travel").attr("checked", true) : "";
}
})
這是Ajax請求被髮送'$( 'travelSwitch')唯一的一次點擊(函數( ){ –
也看到我的更新anwser,有一個初始化ajax請求發送到api設置基於api響應的檢查屬性 –
我試圖使這個更清楚,什麼'$('。travelSwitch') .click(function(){})的作用是每次點擊$('。travelSwitch')'時,瀏覽器就會執行作爲參數傳遞給'.click()'的函數。如果多次調用'$('。travelSwitch')。click(function(){})',那麼瀏覽器將會調用該函數多次執行該行$ ['。travelSwitch')。click(函數(){})'即使你只點擊一次。 – Wail