我參考這篇https://frank1025.pixnet.net/blog/post/350482198-%5Basp.net-c%23%5D-014-%7C-%E5%89%8D%E7%AB%AF%E9%80%8F%E9%81%8Eashx%E9%A0%81%E9%9D%A2%E8%BF%94%E5%9B%9Ejson%E8%B3%87%E6%96%99
但是不知道為何回傳的格式變成string
$.ajax({
type: "GET",
url: url,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "JSON",
success: function (data) {
var obj = data.d;
console.log(obj);
}
});
後端
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetData(string group)
{
SQLDB db = new SQLDB();
string time_s = "2021-10-15 00:00:00.000";
string time_e = "2021-10-15 02:00:00.000";
List<List<string>> par_list = new List<List<string>>();
par_list.Add(new List<string>() { "{ min:'" + time_s + "'}" });
par_list.Add(new List<string>() { "{ max:'" + time_e + "'}" });
string sql = "DECLARE @STime Datetime DECLARE @ETime Datetime DECLARE @FactoryID nvarchar(10) DECLARE @TagName nvarchar(50) " +
"set @STime = '2021-10-15 00:00:00.000' set @ETime = '2021-10-18 00:00:00.000' set @FactoryID = 'KY-T1HIST' set @TagName = 'HPA-5_KW' " +
"exec h_GetTagValuelist @STime ,@ETime ,@FactoryID ,@TagName";
DataTable dt = db.GetDataTable(sql, CommandType.Text);
string d = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
string datatime = Convert.ToDateTime(dt.Rows[i][0].ToString()).ToString("yyyy-MM-dd HH:mm:00");
string v = dt.Rows[i][2].ToString();
Decimal z = 0;
if (v.Length > 0)
{
z = Convert.ToDecimal(v);
if (z > 0)
{
d += "{x:" + "'" + datatime + "'" + ",y:" + z + "\"},";
}
}
//int z = Convert.ToInt32(x);
//d += "{x:" + "'" + datatime + "'" + ",y:" + z + "\"},";
}
par_list.Add(new List<string>() { d });
//轉換為JSON
System.Web.Script.Serialization.JavaScriptSerializer o = new System.Web.Script.Serialization.JavaScriptSerializer();
string datas = o.Serialize(par_list);
//修改格式
datas = datas.Replace("\\", "");
datas = datas.Replace("\"", "");
datas = datas.Replace("u0027", "'");
return datas;
}
你貼的文章是用ashx
結果你用的是webmethod...
好吧直接說重點問題在於你method回傳的就是string...
要直接是json格式要回傳object才對或是List
例如我隨便做一個test class用list包起來回傳
就會變一個陣列型態
程式碼
public class test
{
public string a { get; set; }
public string b { get; set; }
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static object GetData()
{
List<test> data = new List<test>();
data.Add(new test
{
a = "1",
b = "aaa"
});
data.Add(new test
{
a = "2",
b = "bbb"
});
return data;
}
輸出結果
我剛好找到答案,感謝您,就跟你說的一樣
我這邊還有另一個問題,這是目前的資料
然後我希望格式能改成這樣
ddx
你這個應該是陣列裡面又包個陣列而不是定義好Object
而且陣列裡面又是不固定型態所以要用Object的陣列來定義
大概這樣寫
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static object GetData()
{
List<object[]> data = new List<object[]>();
data.Add(new object[]
{
"2021-01-01",
943.64
});
data.Add(new object[]
{
"2021-03-01",
941.22
});
return data;
}
結果
有啦,真的太感謝您了:)
請問你貼的程式碼是完整的嗎?
這個區塊我沒看到,如果只有
public static string GetData(string group)
回傳是字串型態...