发布数据到C#与jQuery和AJAX [英] Posting data to C# with jQuery and AJAX
问题描述
我有一个网站,我已经建立了一个表格。验证后,我想从输入的数据发送到通过AJAX背后的code的方法。我已搜查广泛,我真的不知道为什么它不工作。
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. I have searched extensively and I really have no idea why it's not working.
下面是我的JavaScript / jQuery的
Here is my 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!");
}
});
});
这是我的身后,我试图只返回一个简单的字符串,看看是否所有的值传递code:
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();
}
任何帮助将是AP preciated。我已经工作了几个小时,不能找出我的问题。
Any help would be appreciated. I've been working for a few hours and can't figure out my problem.
推荐答案
您应该添加 $(文件)。就绪()
之前使用jQuery,这里是<一个HREF =http://api.jquery.com/ready/相对=nofollow> DOC
you shall add $(document).ready()
before use JQuery, here is the doc
这是我的code从你的修改,它的工作原理
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);
}
});
});
});
这篇关于发布数据到C#与jQuery和AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!