我正在使用API的MVC应用程序,我想从API调用一个方法,以便它将数据加载到组合框。我不知道如何解决这个问题,因为我是新手。
感谢。
来自获得此功能的API的 ClaimController
函数。
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
来自客户端的视图,即UI 我想从API调用该函数将数据加载到组合框
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
下拉
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>
答案 0 :(得分:0)
获得服务器响应后,必须将选项元素附加到select(下拉)元素中。像这样:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
请参阅jsfiddle https://jsfiddle.net/n4mtj9om/
答案 1 :(得分:0)
如果使用Chrome进入开发人员工具,请查看服务器在服务器响应后如何设置断点的响应,因为可能会使用 把这个
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}