[英]Posting data to C# with jQuery and AJAX
I have a website where I have built a form. 我有一个建立表单的网站。 After validation I want to send the data from the inputs to a method in the code behind via AJAX.
验证之后,我想通过AJAX将数据从输入发送到后面代码中的方法。 I have searched extensively and I really have no idea why it's not working.
我已经进行了广泛的搜索,但我真的不知道为什么它不起作用。
Here is my JavaScript/Jquery 这是我的JavaScript / jQuery
$('#submitForm').click(function() {
var userEmail = $(this).children('.user_email').val();
var userName = $(this).children('.user_name').val();
var userSubject = $(this).children('.user_subject').val();
var userMessage = $(this).children('.user_message').val();
var dataValues = {
'name': userName,
'email': userEmail,
'subject': userSubject,
'message': userMessage
}
dataValues = JSON.stringify(dataValues);
$.ajax({
type: "POST",
url: "Contact.aspx/sendForm",
data: dataValues,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("it worked!");
}
});
});
This is my code behind where I attempt to just return a simple string to see if all the values were passed: 这是我后面的代码,在这里我尝试仅返回一个简单的字符串以查看是否所有值都已传递:
[WebMethod]
public static String sendForm(string name, string email, string subject, string message)
{
return DateTime.Now.ToString();
}
Any help would be appreciated. 任何帮助,将不胜感激。 I've been working for a few hours and can't figure out my problem.
我已经工作了几个小时,无法解决我的问题。
you shall add $(document).ready()
before use JQuery, here is the doc 您应该在使用JQuery之前添加
$(document).ready()
,这是文档
this is my code modified from yours, it works 这是我从您那里修改的代码,可以正常工作
$(document).ready(function () {
$('#submitForm').click(function () {
var userEmail = "email";
var userName = "userName";
var userSubject = "UserSubject";
var userMessage = "UserMesssage";
var dataValues = {
'name': userName,
'email': userEmail,
'subject': userSubject,
'message': userMessage
};
dataValues = JSON.stringify(dataValues);
$.ajax({
type: "POST",
url: "WebForm2.aspx/sendForm",
data: dataValues,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("it worked!" + msg.d);
}
});
});
});
Your contentType: "application/json; charset=utf-8"
is expecting json
, but in C# you are returning string in the function. 您的
contentType: "application/json; charset=utf-8"
需要json
,但是在C#中,您正在函数中返回字符串。 You should return json
您应该返回
json
Here change your code behind function as follows: 在这里,请按以下所示更改功能背后的代码:
[WebMethod]
public static String sendForm(string name, string email, string subject, string message)
{
var mydatedata = DateTime.Now.ToString();
return JSON.stringify({ mydate: mydatedata});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.