如何使用Ajax在asp.net中发布表单数据 [英] How to post form data in asp.net using ajax

查看:106
本文介绍了如何使用Ajax在asp.net中发布表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ajax发布asp.net的表单数据。并希望接收另一个页面形式的阵列上的数据。

I want to post form data of asp.net using ajax. and want to receive that data on another page as form array.

这是要我现在做的
Default2.aspx

this is want I am doing now Default2.aspx

 $('#btnSubmit').click(function () {
            $.ajax({
                type: "POST",
                url: "Default3.aspx",
                data:  $('#form1'),
                success: function (msg) {
                    alert("Success");
                }
            });
        });

和上Default3.aspx

and on Default3.aspx

 protected void Page_Load(object sender, EventArgs e)
    {

        int loop1;
        NameValueCollection coll;

        //Load Form variables into NameValueCollection variable.

        coll = Request.Form;
        // Get names of all forms into a string array.
        String[] arr1 = coll.AllKeys;
        for (   loop1 = 0; loop1 < arr1.Length; loop1++)
        {
            Response.Write("Form: " + arr1[loop1] + "<br>");
            Label1.Text = arr1[loop1];
        }

    }

更新:我通过Ajax调用发送序列化对象。我想在我的asp.net code数据。我该怎么做?

Update : I am sending serialized object through ajax call . I want to that data in my asp.net code. How can i do that ?

推荐答案

使用连载方法。

由于您使用的一种形式可以让它控制怎么办的帖子:

Since you are using a form you can let it control how to do the post:

var $frm = $('#form1');
$('input[type="submit]', $frm).click(function (e) {
    e.preventDefault();

    $.ajax({
        type: $frm.attr('method'),
        url: $frm.attr('action'),
        data:  $frm.serialize(),
        success: function (msg) {
            alert("Success");
        }
    });
});

这可以被重构到一个通用脚本,你可以在你的母版的地方:

Which can be refactored into a generic script that you can place in your masterpage:

<script type="text-javascript">
    $(function() {
        $('.post-using-ajax').each(function() {
            var $frm = $(this);
            $frm.submit(function (e) {
                e.preventDefault();

                $.ajax({
                    type: $frm.attr('method'),
                    url: $frm.attr('action'),
                    data:  $frm.serialize(),
                    success: function (msg) {
                        alert("Success");
                    }
                });
            });
        });
    });
</script>

这让您与CSS类变换各种形式的使用的Ajax后进入AJAX的形式。

<form method="POST" action="someAction" class="post-using-ajax">
    <!-- all form items -->
</form>

这篇关于如何使用Ajax在asp.net中发布表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆