最好使用 MVC 的 @URL.Action 来确保正确编码 URL,即使您的视图是一到十个文件夹。
在上面的示例“/MyController/OptionsAction”中,如果您将视图向下移动一个文件夹,@URL.Action 将继续工作,则该文件夹将不起作用。
注意ajax调用的格式是这样的:
- 发送数据:
网址(您要发帖的地方)
数据(您发布的数据)
type(发出的请求类型:POST 或 GET 或 PUT。如果留空,则默认为 GET)
contentType(向服务器发送数据时使用的内容类型。除非必要,否则最好不要更改)
- 接收数据:
dateType(您期望返回的数据类型:在本例中为 json)
success(请求成功时调用的函数)
$('#Country').autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("GetCountries", "User")',
data: "{ 'CountrySearch': '" + $('#Country').val() + "' }",
dataType: "json",
type: "POST",
contentType: 'application/json',
success: function (data) {
response($.map(data, function (item) {
return JSON.parse(item);
}))
},
error: function (jqXhr, textStatus, errorThrown) { alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')"); },
})
},
minLength: 1,
});
国家从这样的数据库调用中返回数据:
{ "国家":"["澳大利亚", "奥地利", "加拿大", "美国"]" }
public JsonResult GetCountries(string CountrySearch)
{
string[] Countries = new AddressManager().GetCountries(CountrySearch);
string serialisedList = new JavaScriptSerializer().Serialize(Countries);
return new JsonResult { Data = new { Countries = serialisedList }, ContentEncoding = Encoding.UTF8, ContentType = "text/plain", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}