通过AJAX和JQUERY提交.NET简单表单



多亏了balexandre和rtiq,我已经完成了所有流程。我的.ashx文件正在被调用,所以我知道部分代码正在工作,它会提醒我一个错误。当我跟踪.NET时,变量是通过上下文拉进来的。请求["电子邮件"]和上下文。请求["optin"]为NULL。

我知道有什么问题,但我看不出来。我已经重新编辑了这篇文章,以获得最新的代码。

HEAD中的jQuery

<script type="text/javascript">
    $(document).ready(function () {
        $(".submitConnectButton").click(function (evt) {
            evt.preventDefault();
            alert("hello click");
            alert($(".emailConnectTextBox").val());
            $.ajax({
                type: "POST",
                url: "/asynchronous/insertEmail.ashx",
                data: "{email: '" + $(".emailConnectTextBox").val() + "',optin: '" + $(".connectCheckbox").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) { alert(msg.d); },
                error: function (msg) { alert('Error:' + msg); }
            });
        });
    });
</script>

HTML

<div class="emailConnect">
    <asp:TextBox runat="server" ID="TextBox1" CssClass="emailConnectTextBox" BorderStyle="Solid"></asp:TextBox>
              <asp:ImageButton id="connectButton" CssClass="submitConnectButton" runat="server" ImageUrl="~/Images/submit_btn.png" /><br />
    <asp:CheckBox Checked="true" id="checkbox1" runat="server" CssClass="connectCheckbox" />
</div>

.ashx中的CodeBehind

public class insertEmail : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string strConnection = System.Configuration.ConfigurationManager.AppSettings["SQLConnectString"].ToString();
        string email = context.Request["email"],
               optin = context.Request["optin"];
        string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "','" + optin.ToString() + "')";
        SqlConnection Conn = new SqlConnection(strConnection); 
        SqlCommand Command = new SqlCommand(strSQL, Conn);
        Conn.Open();
        Command.ExecuteNonQuery(); 
        Conn.Close(); 
        context.Response.ContentType = "text/plain"; 
        context.Response.Write("email inserted");
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

形式和元素运行正常。我们只是得到了这个NULL值,无法插入。ajax正在正确调用.ashx文件,并且该文件正在编译,请求的变量为null。。之前的帮助太棒了,如果有人能帮我解决最后一个问题,你今天就会得到一颗金星!:)


在离线搜索书籍后,我终于用balexandres.aspx方法得出结论:

解决方案

$.post("/asynchronous/addEmail.aspx", {email: $(".emailConnectTextBox").val(),optin: $(".connectCheckbox").is(':checked')}, function(data) { alert('Successful Submission');});
  • 在您的网站根目录中创建一个名为asynchronous的新文件夹
  • 创建一个名为addEmail.aspx的新aspx页面,并删除除第一行以外的所有HTML
  • addEmail.aspx中,您将代码放在后面,例如:

public void Page_Load(...) 
{
    insertEmail();
}
public void inserEmail() {
    string email = Request["email"],
           optin = Request["optin"];
    string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
    SqlConnection Conn = new SqlConnection(strConnection);
    SqlCommand Command = new SqlCommand(strSQL, Conn);
    Conn.Open();
    Command.ExecuteNonQuery();
    Conn.Close();
    // Output
    Response.Write("email inserted");
}
  • 在具有.ajax()调用的主页中,将url属性更改为

    url: "/asynchronous/insertEmail.aspx",

您将在msgsuccess: function (msg) {}中有字符串email inserted

不过,这是我一直在做的事情,我没有创建ASPX页面,而是使用不包含任何ASP.NET页面周期(加载速度更快)的ASHX(通用处理程序)页面,这是一个简单的页面。


如果您想使用Generic Handler,请在asynchronous文件夹中创建一个名为inserEmail.ashx的文件,完整代码为:

public class insertEmail : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string email = context.Request["email"],
               optin = context.Request["optin"];
        string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
        SqlConnection Conn = new SqlConnection(strConnection);
        SqlCommand Command = new SqlCommand(strSQL, Conn);
        Conn.Open();
        Command.ExecuteNonQuery();
        Conn.Close();
        context.Response.ContentType = "text/plain";
        context.Response.Write("email inserted");
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

并且,请记住将您的url属性更改为url: "/asynchronous/insertEmail.ashx",


从您的评论中,我意识到您的data属性也不正确。

正确的是:

data: { 
        "email" : $(".emailConnectTextBox").val(), 
        "optin" : $(".connectCheckbox").val() },

您的完整ajax调用应该是:

$.ajax({
    type: "POST",
    url: "/asynchronous/insertEmail.ashx",
    data: { 
        "email" : $(".emailConnectTextBox").val(), 
        "optin" : $(".connectCheckbox").val() 
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) { 
        alert(msg.d); 
    },
    error: function (msg) { 
        alert('Error:' + msg.d); 
    }
});

并且通用处理程序中的Response.Write应该传递一个JSON字符串以及

因此,将tgis context.Response.Write("email inserted");更改为context.Response.Write("{d:'email inserted'});

仅此而已。

 $("button").click(function(){
 var content = new Object();
 content.email = $("#email").val();
 content.option = $("#checkbox").val();
 content = JSON.stringify(content);

 $.ajax({
        async: false,
        type: "POST",
        url: aspxPage + "/" + function, //make sure root is set proper.
        contentType: "application/json;",
        data: content,
        dataType: "json",
        success: successFunction,
        error: errorFunction
    });
    });

    //Make sure the form is posted ..which is needed for ajax to submit.
    //the data part in code behind seems ok.

您的html代码中没有表单,因为您可能不使用submit。如rciq所写,请使用click。

尝试更改此项:

$("#connectButton").submit(function () {
    alert("hello click");
    (...)

对此:

$("#connectButton").click(function (evt) {
    evt.preventDefault();
    alert("hello click");
    (...)

此外,您必须记住,ASP.NET服务器控件的ID与呈现的DOM控件ID不同。这可能是您的警报未激发的原因。如果您在与服务器控件相同的页面上编写客户端脚本,则可以通过以下方式在脚本标记内"呈现"ClientID:

$("<%= connectButton.ClientID %>").click( ...

另一件事。如果在HEAD脚本中使用jQuery选项,它们可能会过早启动,无法找到控件。您应该在创建DOM控件后运行它们。要做到这一点,需要使用"就绪"事件:

http://api.jquery.com/ready/

最新更新