我有一张表格
<form method="GET">
<input type="text" class="form-control" id="rent" name="rent" placeholder="Monthly Rent Amount" />
<input type="text" class="form-control" id="streetAddress" name="streetAddress" placeholder="Stress Address" />
<input type="text" class="form-control" id='streetName' name="streetName" placeholder="Stress Name" />
<input type="text" class="form-control" id='city' name="city" placeholder="City" />
<input type="text" class="form-control" id='state' name="state" placeholder="State" />
<input type="text" class="form-control" id='zip' name="zip" placeholder="Zip" />
<button type="submit" id="submitListing" class="btn-primary btn-lg center-block">Submit</button>
</form>
和api的js页面调用
$(document).ready(function () {
$('#submitListing').on('click', function (e) {
var lati;
var lng;
var listData = JSON.stringify({
rent: $('#rent').val(),
streetAddress: $('#streetAddress').val(),
streetName: $('#streetName').val(),
city: $('#city').val(),
state: $('#state').val(),
zip: $('#zip').val(),
lat: lati,
lon: lng
});
e.preventDefault();
$.ajax({
url: contextRoot + "/list/create",
type: "POST",
data: listData,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-type", "application/json");
codeAddress();
},
success: function (data, status) {
// window.location = contextRoot;
},
error: function (data, status) {
alert("bad post");
console.log(data.errors);
}
});
var address = $('#streetAddress').val() + " " + $('#streetName').val() + " " + $('#city').val() + " " + $('#state').val() + " " + $('#zip').val();
function codeAddress() {
$.ajax({
type: "GET",
url: "http://www.LIhb6pFxB7qAlFC4Aiul9rM9i7R5BcgBmapquestapi.com/geocoding/v1/address?key=KEY&location=" + address,
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-type", "application/json");
},
success: function (response, status) {
alert("OK");//alerts OK, but NONE of the followinng
lati = response.results[0].locations[0].latLng.lat;
lng = response.results[0].locations[0].latLng.lng;
console.log(lati, lng);
},
error: function (data, status) {
// alert("geo error");
console.log(data.errors);
}});
}
});
});
我需要做的是在POST运行之前调用GET请求。出于某种原因,无论何时我提交表单,它总是在GET之前进入POST,无论我将它们放入的顺序。我需要在POST之前运行GET以使lat / lng传递给POST。
GET正确返回lat / lng,但直到POST运行。
有人知道为什么会这样吗?