通过ajax将数据发布到数据库中。显示501内部错误

时间:2014-04-14 14:58:06

标签: jquery asp.net ajax json

我正在尝试将我的asp.net webform中的数据发布到数据库中。我在我的asp.net服务(shoppingcart_service.asmx)

中有这个
 [WebMethod] // 
        public void RegisterSubscriber(string Email)
        {
            new OnlineShopTableAdapters.NewsletterSubscribersTableAdapter().Insert(Email, DateTime.Now);
     //database code


        }

这是我的HTML

  <input type="button" onclick="saveData()" id="btnSave" value="Subscribe"  >

这是我的ajax代码,我把它放在一个名为apps.js的文件中并链接到我的页面

//更新了!     function saveData(){

 function saveData() {

    var SubscriberEmail = $("#Email").val();
    $.ajax({
        type: "Post",
        url: "shoppingcart_service.asmx/RegisterSubscriber",
        data: '{"Email":"' + SubscriberEmail + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert(response.status + ' ' + response.statusText);
        },
        error: function (request, status, error) {

        }

    });

}

但是,在点击订阅按钮

后,考虑到Chrome控制台中出现的错误,该值未发布到我的数据库中

error-snapshot

4 个答案:

答案 0 :(得分:0)

我认为问题是ASMX,它不允许在Web方法上发布POST。 这是对类似问题的回答Enable ASP.NET ASMX web service for HTTP POST / GET requests试一试。

答案 1 :(得分:0)

我在其中一个项目中做了同样的事情并且效果很好。我能看到的唯一区别是我的webmethods返回string/bool值,而webservice类也有ScriptService属性。< / p>

见下文:

 [System.Web.Script.Services.ScriptService]
 public class ajaxpost : WebService
 {
     [WebMethod]
     public string Callback(string txbFirstname)
     {
     }
 }

,脚本方是:

    $.ajax({
        type: "POST",
        url: "/Services/ajaxpost.asmx/Callback",
        data: '{"txbFirstname":"' + txbFirstname + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {

        },
        error: function(request, status, error) {

        }

    });

答案 2 :(得分:0)

更改:

url: location.pathname + "shoppingcart_service.asmx/RegisterSubscriber"

url: "shoppingcart_service.asmx/RegisterSubscriber"

没有location.pathname

答案 3 :(得分:0)

谢谢大家,我终于找到了答案,它在我提供webmethod参数的方式中撒谎是有效的代码。

 function saveData2() {
    var SubscriberEmail = $("#Email").val();

    $.ajax({
        type: "POST",
        url: "shoppingcart_service.asmx/RegisterSubscriber",
        data: "email=" + SubscriberEmail, // the data in form-encoded format, ie as it would appear on a querystring
        //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it
        dataType: "text", // the data type we want back, so text.  The data will come wrapped in xml
        success: function (data) {
            $("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper
        }
    });
    }

我不需要在数据行中使用花括号