我使用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, “用户名”: “KARTHIK”, “密码”: “KARTHIK”, “电子邮件”: “karthikdheeraj@gmail.com”} { “ID”:2 “用户名”:” Lohith”, “密码”: “Lohith”, “电子邮件”: “lohith@cnonymn.com”}
和Html为
一种表格结构,其中每个单元格都填充“未定义”
上述代码中的问题可能是什么。
答案 0 :(得分:2)
看起来从服务器检索的json是不正确的,它不是一个对象数组。
正确的格式应为:
[
{"id":1,"username":"karthik","password":"karthik","Email":"karthikdheeraj@gmail.com"},
{"id":2,"username":"Lohith","password":"Lohith","Email":"lohith@cnonymn.com"}
]
这是使用格式正确的数据的plnkr showing your table filling code
答案 1 :(得分:1)
你要回来的JSON还有什么。正确的格式必须是:
var json = [{
"id": 1,
"username": "karthik",
"password": "karthik",
"Email": "karthikdheeraj@gmail.com"
}, {
"id": 2,
"username": "Lohith",
"password": "Lohith",
"Email": "lohith@cnonymn.com"
}];
下面是我创建的小提琴,显示循环现在正确地提醒用户名。 http://jsfiddle.net/77YBq/
经过更多调查:
为了继续深入研究这个问题,我相信你的JSON问题的根源&#34;如果文档是正确的&#34; JsonWriter Documentation
我相信你的服务器代码需要
jsonWriter.WriteStartArray(); // Starts Json Array notation;
// This is your existing code
//================================================================================
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();
//================================================================================
// End of your existing code
jsonWriter.WriteEndArray(); // Ends Json Array notation;
答案 2 :(得分:1)
JsonTextWriter不打算以您使用它的方式使用。
您应该利用序列化库,这样就不会编写代码来序列化JSON。
这是一个使用JSON.NET的解决方案。
在您的解决方案中包含http://json.codeplex.com/处的包裹。
将此using语句添加到您的文件中:
using Newtonsoft.Json;
添加一个类来将您的记录映射到。
public class User{
... properties here
}
[WebMethod]
public static string GetJson2()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var users = new List<User>();
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
users.add(new User { id = reader["id"], username = reader["username"] ..});
}
reader.Close();
}
catch (MySqlException mySqlException)
{ // exception
return mySqlException + "error";
}
return JsonConvert.SerializeObject(users);
}
您还应该考虑将您的ID,用户名等命名为Id,用户名等,以便遵循正确的命名约定。