【发布时间】:2016-03-02 06:32:25
【问题描述】:
我在我的 ajax 请求中包含以下内容:
$(function () {
$("#DropDownList1").change(function () {
alert($("#DropDownList1")[0].value);
$.ajax({
type: "POST",
url: '<%= Page.ResolveUrl("~/bikesearch.aspx/GetModels") %>',
data: '{id: "' + $("#DropDownList1")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (r) {
var ddlCustomers = $("[id*=DropDownList2]");
ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
});
以下是我的 Global.asax 文件的一部分:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("", "bikesearch/{Manufacturer}", "~/bikesearch.aspx");
routes.MapPageRoute("", "bikesearch/{Manufacturer}/{Model}", "~/bikesearch.aspx");
}
以下是我的 WebMethod 返回的内容:
[System.Web.Services.WebMethod]
public static List<ListItem> GetModels(int id)
{
connection conn = new connection();
string query = "SELECT Id, Model FROM Model where Manufacturer_Id = " + id;
using (SqlConnection con = new SqlConnection(conn.GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["Id"].ToString(),
Text = sdr["Model"].ToString()
});
}
}
con.Close();
return customers;
}
}
}
尝试在bikesearch.aspx 页面上触发AJAX 请求时,请求失败。我可能做错了什么?任何帮助表示赞赏。
我注意到下面的 webmethod 在只返回一个字符串时可以正常工作:
[System.Web.Services.WebMethod]
public static string ebulten_Add()
{
return "test";
}
【问题讨论】:
-
请在谷歌浏览器中打开bikesearch.aspx,而Ajax请求捕获开发者工具的网络选项卡(在网络选项卡中过滤xhr)
-
我以前从未使用过这个,我收到了状态 400 错误请求消息。
-
返回字符串的webmethod工作正常,但是返回列表的webmethod失败,这是为什么呢?