我有一个html控件选择 HTML :
<select id="selectGroup" runat="server" name="D1">
</select>
如何使用Web服务JavaScript / jQuery / JSON从SQL Server数据库填充数据?
请不要发布有关如何填充 asp:DropDownList 的答案,因为我已经知道如何执行此操作,因此必须使用选择控件。而且不要在我已经知道该怎么做的后面张贴代码。
我尝试从Web服务中获取数据是好的,但它不会填充或无法选择值。从数据库中获取数据,仅显示第一列值。
网络服务代码:
[WebMethod]
public string GetSelectOptionData() // to show select option in vehiclegroup. //trying
{
string jsondata = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString.ToString());
SqlCommand selectCommand = new SqlCommand("Select VehicleNo from sampleDeviceData", conn);
SqlDataAdapter da2 = new SqlDataAdapter(selectCommand);
DataSet ds2 = new DataSet();
conn.Open();
da2.Fill(ds2, "sampleDeviceData");
DataTable dt = new DataTable();
da2.Fill(dt);
jsondata = DataTableToJSONWithJavaScriptSerializer(dt);
conn.Close();
return jsondata;
}
JAVASCRIPT :
function SelectOptionData() {
var select = document.getElementById("selectGroup");
$("#selectGroup").empty();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ShowTable.asmx/GetSelectOptionData",
data: "{}",
dataType: "json",
cache: false,
success: function (data) {
var filedata = [1];
var elements = Array();
elements = jQuery.parseJSON(data.d);
//alert(elements.length); // shows length of elements (var elements = Array();)
for (var i = 0; i < elements.length; i++) {
filedata.push({
ItemName: elements[i]['VehicleNo']
});
//alert(filedata.length); // shows length of filedata (var filedata = [0];)
//create the option and append to the dropdown
var opt = filedata[i + 1].ItemName;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
},
failure: function (data) {
alert("err in select option");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});}