我正在尝试创建一个在提交时发送电子邮件的网络表单。我创建了一个webmethod,我试图用ajax发布。当我提交时,我的ajax是404ing。这是我的代码。我是初学者,当谈到.net时,我想尝试一下。
$(document).ready(function() {
$('.validate-form').submit(function (e) {
e.preventDefault();
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var email = document.getElementById("email").value;
var data = "{'first name': '" + first_name + "', 'last name': '" + last_name + "', 'fromEmail': '" +
email + "'}";
console.log("data", data)
$.ajax({
type: "POST",
url: "SendMessage.aspx/SendMessages",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).fail(function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
})
});
public partial class Send : System.Web.UI.Page
{
[WebMethod]
public static void SendMessages(string first_name, string last_name, string email, string comments)
{
const string SERVER = "zebra.aa.org";
const string TOEMAIL = "adhsaj@am.org";
MailAddress from = new MailAddress(email);
MailAddress to = new MailAddress(TOEMAIL);
MailMessage message = new MailMessage(from, to);
message.Subject = "Web Site Contact Inquiry from " + first_name + last_name;
message.Body = "Message from: " + first_name + last_name + " at " +
email + "\n\n" + comments;
message.IsBodyHtml = false;
SmtpClient client = new SmtpClient(SERVER);
client.Send(message);
Console.WriteLine(message);
}
}
答案 0 :(得分:0)
看起来问题是网址。客户端无法找到Web方法,因为URL不存在。尝试更改
url: "SendMessage.aspx/SendMessages"
到
url: "Send/SendMessages"
答案 1 :(得分:0)
尝试将您的URl更新为Send.aspx/SendMessages
使用
也会更好JSON.stringify({ first_name : first_name, last_name : last_name, email : email, comments : comments })
您没有以方法所需的格式传递所需数据。例如,我看到第一个参数是aspx方法的first_name,但是你的JSON在字符中有一个空格。请更正此并检查。