使用ajax调用代码隐藏方法

时间:2015-11-14 04:35:40

标签: jquery ajax

我使用ajax从html页面调用我的静态Web方法。但它没有点击我的方法,而是重新加载页面。我的脚本在

下面
$(document).ready(function() {
          $("#btnSave").click(function () {
              alert("Clicked");
              var name = $("#txtFirstName").val();
              alert(name);
        // do the extra stuff here
          $.ajax({
          type: "POST",
          url: "AddEditStudent/SaveData",
          data: '{name: "' + name + '" }',

          success: function() {
          //$('.simple-sucess').fadeIn(100).show();
          //$('.contact_form').fadeOut(100).hide();
          // $('.simple_error').fadeOut(100).hide();

          },
          failure: function () {
              alert("fail");
          }

我的代码隐藏方法

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {

    }
}


[WebMethod]
    public static string SaveData(string name)
    {
        return "hello";
    }

1 个答案:

答案 0 :(得分:1)

这里的问题是,当您单击提交按钮时,您没有阻止表单的默认操作,这就是为什么它仍然重新加载页面。

要解决此问题,请使用e.preventDefault();

而不是触发点击的yum按钮,您应该在提交表单后触发它。

e.g。

PKGS=$(find "$RPM_DIR" -iname "*.rpm" -type f -exec rpm -qp --qf "%{NAME} " {} \; | sed 's/ $//')
RPMS=$(find "$RPM_DIR" -iname "*.rpm" -type f | awk '{print}' ORS=' ')

if [ "$INTERACTIVE" != true ]; then
  sudo yum -y --disablerepo=* remove $PKGS
  sudo yum -y --nogpgcheck localinstall $RPMS
else
  sudo yum --disablerepo=* remove $PKGS
  sudo yum --nogpgcheck localinstall $RPMS
fi