2

我已经阅读了对同一问题的其他回复,但无法解决这个问题。我正在尝试将 JSON 字符串发布到我的服务器(.NET),对其进行解析并存储一些值 - 代码如下。一切正常(即数据最终在我的数据库中,但它仍然抛出 500 错误)。已经用 Fiddler 等进行了调查,但没有成功

我的代码中可能还有很多其他问题 - 现在只是进行一些实验,但不胜感激任何建议......

首先,jQuery 帖子:

function PostData(value) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/PostData",
            data: JSON.stringify({ postedData: value }),
            contentType: "application/json",
            dataType: "json",
            success: function (msg) {
                console.log("success: " + msg.d);
            },
            error: function (xhr, textStatus, error) {
                console.log("error:" + xhr.statusText + "  " + textStatus + "  " + error);
            }
        });
    }

接下来,服务器端的齿轮:

[WebMethod]
public static string PostData(string postedData)
{
    _PostData(postedData);
    return null;
}

public static void _PostData(string postedData)
{
    JObject o = JObject.Parse(postedData);
    string id = (string)o.SelectToken("id");

    using (SqlConnection sql = new SqlConnection(connectionString))
    using (SqlCommand cmd = sql.CreateCommand())
    {
        try
        {
            cmd.CommandText = "INSERT into Table1 (userId, data) VALUES (@userIdValue, @dataValue)";
            cmd.Parameters.AddWithValue("@userIdValue", id);
            cmd.Parameters.AddWithValue("@dataValue", postedData);

            sql.Open();
            cmd.Connection = sql;
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}
4

0 回答 0