gpt4 book ai didi

Jquery Ajax - 返回 bool 值?

转载 作者:行者123 更新时间:2023-12-03 22:44:50 27 4
gpt4 key购买 nike

新手问题,试图查明电子邮件是否已发送并显示结果,似乎无法使其正常工作。

function SendPreview() {
var value = CKEDITOR.instances['Source'].getData();
alert(value);
var model = { EmailBody: value.toString(), EmailTo: $("#SendTo").val(), EmailSubject: $("#Subject").val() };
var request = $.ajax({
url: '/Campaign/SendPreviewEmail',
async: false,
type: 'POST',
dataType: 'JSON',
data: { model: JSON.stringify(model) },
cache: false,
success: function (data) {
if (data) {
alert("Message Sent");
} else {
alert("Message Not Sent, Please check details");
}
}
});
}
[HttpPost]
[ValidateInput(false)]
public bool SendPreviewEmail(string model)
{
var e = new EmailPreview();
JavaScriptSerializer objJavascript = new JavaScriptSerializer();

e = objJavascript.Deserialize<EmailPreview>(model);
if (!string.IsNullOrEmpty(e.EmailTo) && !string.IsNullOrEmpty(e.EmailSubject) && !string.IsNullOrEmpty(e.EmailBody))
{
if (IsValidEmail(e.EmailTo))
{
_mailService.SendMail(account.Email, e.EmailTo, e.EmailSubject, e.EmailBody, true);
return true;
}
}
return false;
}

最佳答案

假设这是 ASP.Net MVC,您应该从操作中返回一个 ActionResult (或者至少是从它派生的东西)。下一个问题是,返回 true 将意味着将对 bool 值调用 toString(),从而产生字符串 "True ”“False”。请注意,这两者都等同于 javascript 中的 true。相反,返回包含结果标志的 JSON。

在 jQuery 代码中,您还设置了 async: false,这确实是不好的做法。事实上,如果您检查控制台,您会看到浏览器关于其使用的警告。您应该删除该属性,以便异步发出 AJAX 请求。您还在 ajax() 调用中将 dataType 设置为 JSON,但实际上返回的是字符串。试试这个:

function SendPreview() {
var value = CKEDITOR.instances['Source'].getData();
var model = { EmailBody: value.toString(), EmailTo: $("#SendTo").val(), EmailSubject: $("#Subject").val() };
var request = $.ajax({
url: '/Campaign/SendPreviewEmail',
type: 'POST',
dataType: 'JSON',
data: { model: JSON.stringify(model) },
cache: false,
success: function (data) {
if (data.emailSent) { // note the object parameter has changed
alert("Message Sent");
} else {
alert("Message Not Sent, Please check details");
}
}
});
}
[HttpPost]
[ValidateInput(false)]
public ActionResult SendPreviewEmail(string model)
{
var e = new EmailPreview();
var result = false;
JavaScriptSerializer objJavascript = new JavaScriptSerializer();

e = objJavascript.Deserialize<EmailPreview>(model);
if (!string.IsNullOrEmpty(e.EmailTo) && !string.IsNullOrEmpty(e.EmailSubject) && !string.IsNullOrEmpty(e.EmailBody))
{
if (IsValidEmail(e.EmailTo))
{
_mailService.SendMail(account.Email, e.EmailTo, e.EmailSubject, e.EmailBody, true);
result = true;
}
}
return Json(new { emailSent = result });
}

关于Jquery Ajax - 返回 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18652548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com