前台代码:<script type=”text/javascript”>
$(document).ready(function(){
$.ajax({
type: “post”,
url: “test4.aspx/GetSupplier”, //后台webservice里的方法名称
dataType: “json”,
contentType: “application/json;charset=utf-8”,
data: “{}”,
traditional: true,
success: function(data) {
for (var i in data) {
var jsonObj = $.parseJSON(data[i]);
var optionstring = “”;
for (var item in jsonObj) {
jsonObj = eval(“(“+jsonObj.Table+”)”);
for (i = 0; i < jsonObj.length; i++) {
optionstring += “<option value=”” + jsonObj[i].id + “” >” + jsonObj[i].name + “</option>”;;
}
// alert(optionstring);
}
$(“#ddl1”).html(optionstring);
}
},
error: function(msg) {
alert(“出错了!”);
}
});
});
<div>
<select id=”ddl1″ name=”supplier”></select>
</div>
后台代码是:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
///绑定供应商
public static string GetSupplier()
{
string ReturnValue = string.Empty;
string sql = “select deptid, name from network_department where canuse=”0″”; //sql语句
C_DataCommon dcCommon=new C_DataCommon();
DataTable dt = dcCommon.GetDataTable(sql); //数据库帮助类 返回databale类型
ReturnValue = DataTableJson(dt);
return ReturnValue;
}
#region dataTable转换成Json格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name=”dt”></param>
/// <returns></returns>
public static string DataTableJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
//jsonBuilder.Append(“”);
// jsonBuilder.Append(dt.TableName.ToString());
jsonBuilder.Append(“{“”);
jsonBuilder.Append(dt.TableName.ToString());
jsonBuilder.Append(“”:[“);
//jsonBuilder.Append(“”[“);
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append(“{“);
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append(“””);
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append(“”:””);
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append(“”,”);
}
jsonBuilder.Remove(jsonBuilder.Length – 1, 1);
jsonBuilder.Append(“},”);
}
jsonBuilder.Remove(jsonBuilder.Length – 1, 1);
//jsonBuilder.Append(“]””);
// jsonBuilder.Append(“””);
jsonBuilder.Append(“]”);
jsonBuilder.Append(“}”);
return jsonBuilder.ToString();
}
#endregion
运行的时候,出现这个错误,这哪里不对啊,用dropdownlist的绑定数据我会,但是用JS在table里面动态添加行的时候,好像并不能放服务器控件,只能放HTML的,所以想到用select动态绑定数据了