我正在使用 PageMethod 使用以下 C# 代码以 Json 格式检索表数据
[WebMethod]
public static string GetJson2()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
try
{
string connstr = "server=localhost;user=root;database=cm_users;port=3306;password=root";
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = "select * from users";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int fieldcount = reader.FieldCount; // count how many columns are in the row
object[] values = new object[fieldcount]; // storage for column values
reader.GetValues(values); // extract the values in each column
jsonWriter.WriteStartObject();
for (int index = 0; index < fieldcount; index++)
{ // iterate through all columns
jsonWriter.WritePropertyName(reader.GetName(index)); // column name
jsonWriter.WriteValue(values[index]); // value in column
}
jsonWriter.WriteEndObject();
}
reader.Close();
}
catch (MySqlException mySqlException)
{ // exception
return mySqlException + "error";
}
// END of method
// the above method returns sb and another uses it to return as HTTP Response...
string jsonString = sb.ToString();
return jsonString; ;
}
现在我正在使用 Java Scipt 将方法的输出捕获到 html 页面中
使用 Ajax JavaScript 我正在使用 Json 格式的返回字符串。
function getUsers() {
$.ajax({
type: "POST",
url: "http://{address}:8078/Default.aspx/GetJson2",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
var myTable1 = '';
myTable1 += '<table id="myTable1" cellspacing=0 cellpadding=2 border=1>';
myTable1 += "<tr><td><b>ID</b></td><td><b>UserName</b></td><td><b>Password</b></td><td><b>Email</b></td></tr>";
$.each(msg, function(i,v){
alert(i + v);
myTable1 += "<tr><td>" + v.id + "</td><td>" + v.username + "</td><td>" + v.password + "</td><td>" + v.Email + "</td></tr>";
});
$("#user_tb1").html(myTable1) ;
},
error: function () {
alert("error");
}
});
};
我将 Json 字符串作为
{"id":1,"username":"karthik","password":"karthik","Email":"karthikdheeraj@gmail.com"}{"id":2,"username":"Lohith", "密码":"Lohith","电子邮件":"lohith@cnonymn.com"}
和 HTML 作为
一个表格结构,其中每个单元格都填充有“未定义”
上面代码中的问题可能是什么。