Jquery Ajax - 返回布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18652548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Ajax - Return Bool?
提问by D-W
newbie question, trying to find out if an email sent, and show result, cant seem to get it to work.
新手问题,试图找出是否发送了电子邮件并显示结果,似乎无法使其正常工作。
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;
}
回答by Rory McCrossan
Assuming this is ASP.Net MVC, you should be returning an ActionResult
from your action (or at least something that derives from it). The next issue is that returning true
will mean toString()
will be called on the bool
value, resulting in the string "True"
or "False"
. Note that both of these equate to true
in javascript. Instead, return JSON containing a result flag.
假设这是 ASP.Net MVC,你应该ActionResult
从你的动作中返回一个(或者至少是从它派生的东西)。下一个问题是返回true
将意味着toString()
将调用该bool
值,从而产生字符串"True"
or "False"
。请注意,这两个都等同于true
在 javascript 中。相反,返回包含结果标志的 JSON。
In the jQuery code you've also set async: false
which is really bad practice to use. In fact, if you check the console you'll see browsers warnings about its use. You should remove that property so that the AJAX request is made asynchronously. You've also set dataType
to JSON
in the ajax()
call, but are actually returning a string. Try this instead:
在 jQuery 代码中,您还设置了使用async: false
哪种做法非常糟糕。事实上,如果您检查控制台,您会看到浏览器有关其使用的警告。您应该删除该属性,以便异步发出 AJAX 请求。你也已经安排dataType
到JSON
在ajax()
通话,但实际上是返回一个字符串。试试这个:
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 });
}
回答by The Alpha
Actually return
doesn't send anything back to the browser, you have to write data to be sent back to the browser, probably Response.Write
, not a familiar with this.
实际上return
不会向浏览器发送任何内容,您必须编写要发送回浏览器的数据,可能Response.Write
,对此不熟悉。
Also, on the client side
此外,在客户端
if (data)
is same for any data, it'll evaluate to true if any data sent back to the browser, so need to check actual data, could be something like this
对于任何数据都是相同的,如果有任何数据发送回浏览器,它将评估为真,因此需要检查实际数据,可能是这样的
if (data == 1)
Or, for json, it could be
或者,对于 json,它可能是
if (data.success) // if you send a json response.