我希望这是一个相当简单的json问题。我有一个联系页面,我使用jquery函数将数据发送到c#sendmail方法。这一切都有效。我发送信息回到jquery但有麻烦。
我的c#是:
if (!ok)
{
return Json(new { success = false, responseText = "FAIL" },
JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = true, responseText = "SENT" },
JsonRequestBehavior.AllowGet);
}
和jquery的ajax部分是:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
cache:false,
url: "x/sendEmail",
dataType: 'json',
data: JSON.stringify(myData),
//complete changed to success
success: function (response) {
if (response != null && response.success) {
alert(response.success + " pass" + response.responseText);
} else {
alert(response.success + " fail " + response.responseText);
}
},
error: function (response) {
alert(response.success + " fail2 " + response.responseText);
}
我将response.success视为true或false,但response.responseText始终是' undefined'。
不确定我缺少什么
我改变了C#,但结果相同
public class ResponseObject
{
public bool success { get; set; }
public string responseText { get; set; }
}
public ActionResult sendEmail(string userName, string userEmail, string
userPhone, string userAddress,string userSubject, string userMessage, string
userList)
{
///code to send mail - works no problem
ResponseObject response;
if (!ok)
{
// Send "false"
response = new ResponseObject { success = false, responseText = "FAIL" };
}
else
{
// Send "Success"
response = new ResponseObject { success = true, responseText = "Your message successfuly sent!" };
}
return Json(response, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
请尝试返回Content
(您将需要Newtonsoft.Json包)
public ActionResult sendEmail(string userName, string userEmail,string userPhone, string userAddress, string userSubject, string userMessage, string userList)
{
///code to send mail - works no problem
if (!ok)
{
// Send "false"
var response = new { success = false, responseText = "FAIL" };
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(response), "application/json");
}
else
{
// Send "Success"
var response = new { success = true, responseText = "Your message successfuly sent!" };
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(response), "application/json");
}
}
答案 1 :(得分:0)
按F12打开开发。工具,转到"网络"选项卡并再次进行AJAX调用。现在您应该能够找到调用sendEmail函数的URL。点击它,转到"响应"选项卡,查看服务器发送的响应。在那里,您将能够验证您是否同时接收所使用的属性和使用的格式(例如,可能是属性名称中的拼写错误)。