我有asp.net mvc web api 2 url。我需要使用那个Web API数据集成到PHP应用程序搜索和数据(邮政编码显示列表)自动完成。这些在我的jQuery和PHP搜索页面代码下面,但它不适合我。请告诉我为什么会这样?
这是asp.net mvc web api 2 JSON返回值。
[{"ID":6,"SuburbName":"Carlton North","postcode":"3054","Territory":"MEL-Brunswick","Latitude":- 37.7845911,"Longitude":144.972883,"AuState":"VIC","created":"13/03/2015 12:00:00 AM","updated":"13/03/2015 12:00:00 AM"}
[{"ID":7,"SuburbName":"Carlton South","postcode":"3054","Territory":"MEL-Brunswick","Latitude":- 37.7845911,"Longitude":144.972883,"AuState":"VIC","created":"13/03/2015 12:00:00 AM","updated":"13/03/2015 12:00:00 AM"}
这是我的jQuery代码
var searchRequest = null;
$(".auto").autocomplete({
maxLength: 5,
source: function(request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: 'asp.net mvc api web url',
method: 'post',
dataType: "json",
data: {term: request.term},
success: function(data) {
searchRequest = null;
response($.map(data.items, function(item) {
return {
value: item.SuburbName,
label: item.SuburbName
};
}));
}
}).fail(function() {
searchRequest = null;
});
}
});
<form method="POST" action="search.php">
Enter your Postcode:
<input type="text" name="search" >
<input name="submit" type="submit" class="auto" value="<?php echo $_POST['search'];?>" /><br />
</form>
if(isset($_POST['submit']))
{
$value=$_POST['search'];
}
答案 0 :(得分:1)
不确定你走了多远,但一个解决方案是从服务器(PHP)或WebAPI包装http请求,并允许自动完成使用本地请求:
public IEnumerable<Locations> GetLocations(string pcode)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.tlcnewsletter.com.au/api/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/values?pcode=" + pcode).Result;
if (response.IsSuccessStatusCode)
{
var res = response.Content.ReadAsAsync<IEnumerable<Locations>>().Result;
return res;
}
return null;
}
public class Locations
{
public string ID { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string SuburbName { get; set; }
public string Territory { get; set; }
public string postcode { get; set; }
}
客户端,你说得对:
$(document).ready(function () {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
url: "/api/values",
dataType: "json",
type: 'GET',
data: { pcode: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
value: item.SuburbName,
label: item.SuburbName
};
}));
}
});
}
});
});
结果如下: