【发布时间】:2017-12-01 04:23:51
【问题描述】:
所以我正在向我的控制器发送一个 ajax 请求进行处理。 但是当我在我的 ajax done 函数中 console.log 消息时,它会显示两个结果。
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) : "";
}
})
【问题讨论】:
标签: c# jquery ajax asp.net-mvc api