简体   繁体   English

Ajax调用总是返回错误500客户端

[英]Ajax call always returning error 500 client side

Im trying to post data back to a webmethod located in Default.aspx 我试图将数据发布回位于Default.aspx中的web方法

jquery code: jQuery代码:

data = "{'saveData':'testtestest'}"

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Default.aspx/SavePins",
        data: data,
        dataType: "json",
        success: function (response) {
            if (response.d) {
                //    var obj = JSON.parse(response.d);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#modalContentBox').html('Whoops! There was an error saving!').removeAttr('class').attr('class', 'alert alert-error');
            $('#myModal').modal();
        }
    });

Web Method: 网络方法:

[WebMethod]
public bool SavePins(string saveData)
{
    try
    {
        File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"), saveData);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

The issue is that the Ajax call always returns an error 500 client side. 问题是Ajax调用总是返回错误500客户端。 It does not actually post to the server. 它实际上并不发布到服务器。 there is a <form> element with runat="server" in the page. 页面中有一个带有runat="server"<form>元素。 I've added <asp:ScriptManager EnablePageMethods="True" runat="server"/> 我添加了<asp:ScriptManager EnablePageMethods="True" runat="server"/>

You need to ScriptMethod to your web method because you needs to send the response as json. 您需要ScriptMethod到您的Web方法,因为您需要将响应作为json发送。

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]      
public bool SavePins(string saveData)
{
     try
      {
           File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"),     saveData);
           return true;
      }
     catch (Exception)
     {
        return false;
      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM