使用Asp.net Ajax不显示警报消息

时间:2018-12-24 11:54:52

标签: asp.net json ajax webforms

使用Asp.net将记录添加到数据库中后,不会显示警报消息Ajax.record已成功添加到数据库中。未显示警报。我将代码附加到下面到目前为止尝试的代码下面。添加记录后,如何返回到ajex成功函数以显示alert(“ success”);

表单设计

<form  id="frmProject" runat="server">
            <div>
                <label class="form-label">First Name</label>     
               <input type="text" id="fname" class="form-control"  />
            </div>
            <div class="form-group" align="left">
             <label class="form-label">Age</label>
                <input type="text" id="age" class="form-control"  />
            </div>
            <div> 
               <input type="button" id="b1" value="add" class="form-control" onclick="addProject()" />

            </div>
        </form>

Ajex

  function addProject() {
                $.ajax({
                    type: 'POST',
                    url: 'insert.aspx',
                    dataType: 'JSON',
                    data: {fname: $('#fname').val(), age: $('#age').val()},
                    success: function (data) {         
                        alert("success");
                        get_all();
                    },
                    error: function (xhr, status, error) {
                        console.log(xhr.responseText);
                    }
                });

                }

insert.aspx

 public static string GetData(string fname, int age)
            {
                SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
                string sql = "insert into record values('" + fname + "','" + age + "')";
                SqlCommand cmd = new SqlCommand(sql, con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                return HttpContext.Current.Session.SessionID;
            }  

1 个答案:

答案 0 :(得分:1)

使用Web方法进行Ajax请求

[WebMethod(EnableSession= true)]
public static string GetData(string fname,int age)    
{    
   // place your logic here
   return HttpContext.Current.Session.SessionID;    
}

您的Ajax请求

$('#b1').click(function () {
    jQuery.ajax({
        url: 'insert.aspx/GetData',
        type: "POST",
        data: {fname: $('#fname').val(), age: $('#age').val()},
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert(JSON.stringify(data));
        }
    });
});