我在ASP.NET WebForms网站上有以下ajax电子邮件提交例程:
页面为用户提供输入对话框,他在其中输入数据。 数据打包成json,如下所示:
var name = $("[id$='clientName']");
var phone = $("[id$='clientPhone']");
var serviceType;
var serviceCost;
$("#SubmitOrder").click(function () {
var currName = name.val();
var currPhone = phone.val();
var json = "{'ClientName':'" + escape(name.val()) + "','ClientPhone':'" + escape(phone.val()) + "','ServiceType':'" + serviceType + "','ServiceCost':'" + serviceCost + "'}";
var ajaxPage = "/sendmail.aspx?Send=1";
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
$("#ResMsg").html(response);
},
error: function (msg) { alert("failed: " + msg); }
};
$.ajax(options);
});
并发送到sendmail.aspx进行游行。 sendmail.aspx只是一个webforms页面,在调试时,工作得很好。它正确接收并解析JSON,然后启动异步邮件发送例程。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
SendMail();
}
private void SendEmail()
{
//Bunch of parsing and mail sender init
mailSender.MessageSent += new MessageSentEventHandler(OnMessageSent);
//Here we have subscribed to an async event that occurs when mail sender is done.
// Other unimportant stuff
mailSender.SendMessage(settings["mail.feedback.to.name"], settings["mail.feedback.to.email"], settings["mail.feedback.subject"], body);
}
void OnMessageSent(object sender, MessageSentEventArgs args)
{
if (args.Status == MailSentStatus.Sent)
{
Response.Write("Everything is fine");
}
else
{
Response.Write("Oops. Error!");
}
}
问题:
在我的客户端页面上,每当收到邮件发件人的回复时,我都会收到
失败:[object Object]消息框。
显然我的error:
方法被执行而不是success:
。但邮件发件人发送邮件就好了。
从ASP.NET响应jquery .ajax()调用的正确方法是什么?在我的情况下,我做错了什么?
答案 0 :(得分:4)
你告诉$.ajax
期待dataType: "json"
,所以它正在尝试(并且失败)将返回的HTML解析为JSON。