【发布时间】:2019-05-21 23:53:46
【问题描述】:
我有一个 ajax/json/c# 问题。我想我正在做我在其他帖子中读到的所有内容,但仍然无法正常工作。很可能是飞行员错误,但我错过了。
任何想法表示赞赏。
从电子邮件表单中获取数据并发送到控制器以发送电子邮件。电子邮件已发送!这行得通。
我尝试将数据返回到 ajax,但这似乎不起作用。
[HttpPost]
public JsonResult Sendemail(EmailStuff emailstuff)
{
string msg = sendmail(emailstuff); //this works fine - msg is returned as "ok"
if (msg=="ok")
{
SendAutoReply();// this gets done
return Json(new { success = true, message = msg }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = false, message = msg }, JsonRequestBehavior.AllowGet);
}
//jquery
$('#emailbtn').on('click', function (event) {
//...get form data...
var myData = {
UserName: name, UserEmail: email, UserPhone: phone, UserAddress: address,
UserSubject: subject, UserMessage: msg, UserList: emList
};
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
processData: false,
dataType: "json",
url: $('#baseurl').text() + "email/sendemail",
data: JSON.stringify(myData),
success: function (response) {
if (response.success === true) {
window.location = "email-ok";
} else {
window.location = "email-error?msg="+response.message;
}
},
error: function (response) {
window.location = "email-error?msg=uhoh";
})
})
在控制器中,字符串 msg 设置为“ok”。
我的期望是触发 ajax success: 函数,然后 if 语句将评估 response.success 并重定向到 email-ok 或 email-error 页面。
但是会发生错误:调用函数并且重定向到带有消息“uhoh”的电子邮件错误页面
我知道要做的唯一测试是 Chrome DevTools>Network>XHR>Preview 这表明:加载响应数据失败
所以看起来响应对象没有正确发送。
提前致谢
编辑 响应标头显示 500 错误 - 不确定是什么
Response Header from Dev Tools
cache-control: private
cf-ray: 4daaae4d1eca9f46-IAD
content-type: text/html; charset=utf-8
date: Wed, 22 May 2019 00:30:20 GMT
expect-ct: max-age=604800, report-uri="https://report-
uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 500
x-aspnet-version: 4.0.30319
x-aspnetmvc-version: 5.2
x-powered-by: ASP.NET
编辑 2
如下图第二行出现错误,错误提示“加载资源失败,服务器响应状态为 500”
//line 3954 of jquery-3.2.1.min.js.formatted
try {
h.send(b.hasContent && b.data || null)
} catch (i) {
if (c)
throw i
}
【问题讨论】:
-
Chrome 开发工具中的请求标头是什么样的?
-
@marven - 我确实有 JsonRequestBehavior.AllowGet)
-
@AaronHolland - 我想响应标题中有趣的是我收到了 500 错误 - 我将在上面发布
-
您能分享一下 SendAutoReply 代码吗?或者你可以通过注释那行代码来尝试
-
我发现了一个错误 - 如上面的编辑 2 所示 - 在 jquery 深处,如果我能理解它可能会解释它。上午 1206 点,所以现在不要深入研究 jquery。任何对此有更多了解的人(几乎所有人) - 非常感谢您的帮助
标签: c# json ajax model-view-controller