我创建了一个脚本,需要2个POST代码和返回的距离,如果距离不到4英里,它返回一个成功的消息,如果是4英里,返回另一条消息。如果表单域为空,它也应该抛出一个错误。AJAX请求无法工作
我很想能够无需刷新页面,但到目前为止,我似乎无法得到Ajax请求的工作返回数据,它只是没有做任何事情。
jQuery是不是我的专长我通过网上搜索拼凑了一起。
$(document).ready(function() {
$('#postcode-form').submit(function (event) {
event.preventDefault();
$('.help-block').remove(); // remove the error text
var formData = {
'destination': $('input#destination').val()
};
$.ajax({
type: 'POST',
url: 'includes/postcode-finder.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
if (!data.success) {
if (data.errors.destination) {
$('#destination-group').append('<div class="help-block">' + data.errors.destination + '</div>');
}
} else {
$('#postcode-form').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
});
});
和PHP代码:
$面包店= 'DH12XL'; $ destination = $ _POST ['destination'];
$errors = [];
$result = [];
if(empty($destination))
{
$errors['postcode'] = 'Postcode is required';
}
if(!empty($errors))
{
$data['success'] = false;
$data['errors'] = $errors;
}
else
{
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$bakery&destinations=$destination&mode=bicycling&language=en-EN&sensor=false&units=imperial";
$google = @file_get_contents($url);
$result = json_decode($google, true);
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$many_miles = str_replace(' mi', '', $distance);
if($many_miles > 4.0)
{
$data['message'] = 'Collection only for this postcode';
}
else
{
$data['message'] = 'Good news, we deliver!';
}
$data['success'] = true;
echo json_encode($data);
}
你在浏览器的控制台中查看过看看是否有任何错误? –
他们应该在问题编辑器中为该问题创建一个复选框。 “在发表这个问题是这样,请确保您有......” – GolezTrol
@JayBlanchard我希望我有一分钱每次我不得不张贴血腥评论:) –