简体   繁体   English

在Ajax WebMethod中生成一个json字符串,并将其发送回aspx

[英]Generate a json string in a Ajax WebMethod and send it back to the aspx

I am trying to generate a json string in a Ajax WebMethod and send it back to the aspx success result and printout the results. 我试图在Ajax WebMethod中生成一个json字符串,并将其发送回aspx成功结果并打印出结果。 The json2 string is not correct. json2字符串不正确。 Any suggestions? 有什么建议么?

Default.aspx.cs Default.aspx.cs

    [System.Web.Services.WebMethod]
    public static string GetJSONdata(string id)
    {
        string json2 = "";
        string val = "1;2;3;4;5";
        string[] arr = val.Split(';');
        string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
        string cmdStr = "SELECT ([datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
        try
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@idd", id);
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if (rdr.Read())
                        {
                            arr[1] = rdr[1].ToString();
                            arr[2] = rdr[2].ToString();
                            arr[3] = rdr[3].ToString();
                            arr[4] = rdr[4].ToString();
                        }
                    }
                    conn.Close();
                    cmd.Dispose();
                    conn.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        json2 = "{'datajson' : [{'id' : '" + id + "', 'datetime' : '" + arr[1] + "', 'col1' : '" + arr[2] + "', 'col2' : '" + arr[3] + "', 'col3' : '" + arr[4] + "'}]}";
        return json2;
    }

Default.aspx Default.aspx的

<script type="text/javascript" src="~/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%= Button1.ClientID %>").click(function () {
            var id = $("#<%= TextBox1.ClientID %>").val();
            var data = { ID:id };
            var json1 = JSON.stringify(data);
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetJSONdata",
                data: json1,
                dataType: "json",
                success: function (result) {
                    $("#<%= TextBox2.ClientID %>").val(result.datajson[0].id);
                    $("#<%= TextBox3.ClientID %>").val(result.datajson[0].datetime);
                    $("#<%= TextBox4.ClientID %>").val(result.datajson[0].col1);
                    $("#<%= TextBox5.ClientID %>").val(result.datajson[0].col2);
                    $("#<%= TextBox6.ClientID %>").val(result.datajson[0].col3);
                },
                error: function (Msg) {
                    $("#<%= Label1.ClientID %>").text('failed:' + Msg.status +  '    response:' + Msg.responseText);

                }
            }); return false;
        });
    });

Error code: 错误代码:

failed:500 response:{"Message":"Invalid web service call, missing value for parameter: \u0027id\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
 at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
 at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
 at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
  1. The post keys must match 帖子键必须匹配
  2. Don't stringify the data 不要对数据进行分类
  3. Use a library to build JSON don't do it manually (see @joe comment) 使用库构建JSON无需手动进行(请参阅@joe注释)

ajax: AJAX:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Default.aspx/GetJSONdata",
    data: {clientId : id },
    success: function (result) {...},
    error: function (Msg) {...}
});

C#: C#:

[System.Web.Services.WebMethod]
public static string GetJSONdata(string clientId){...}

Building JSON: 构建JSON:

Use a library , JSON.NET is a good one. 使用一个库,JSON.NET是一个很好的库。 The way it works, you create a model: 创建模型的方式如下:

public class Datajson
{
    public string id { get; set; }
    public string datetime { get; set; }
    public string col1 { get; set; }
    public string col2 { get; set; }
    public string col3 { get; set; }
}

Then use it to build your string 然后用它来构建你的字符串

List<Datajson> data = new List<Datajson>();
Datajson json = new Datajson();
json.id = clientId;
json.datetime = rdr[1].ToString();
json.col1 = rdr[2].ToString();
json.col2 = rdr[3].ToString();
json.col3 = rdr[4].ToString();
data.add(json);

var jsonString = JsonConvert.SerializeObject(data);

then log it to see. 然后登录查看。

Just a guess... 只是个猜测...
But you're expecting "id" in GetJSONdata while you're sending "ID" in ajax request. 但是,在ajax请求中发送“ ID”时,您会在GetJSONdata中期待“ id”。 Might want to keep both of them consistent 可能希望使两者保持一致

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

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