2014-05-22 284 views
0

我创建了一个脚本,需要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); 
} 
+4

你在浏览器的控制台中查看过看看是否有任何错误? –

+1

他们应该在问题编辑器中为该问题创建一个复选框。 “在发表这个问题是这样,请确保您有......” – GolezTrol

+1

@JayBlanchard我希望我有一分钱每次我不得不张贴血腥评论:) –

回答

2

你使用jQuery 1.4.4,它不从$.ajax返回Promises因此.done()功能不可用。

你有两个选择:

更新的jQuery(确保你测试什么事,那就是靠着它,如果你这样做,但!)

或者使用成功参数,而不是:

$.ajax({ 
    type: 'POST', 
    url: 'includes/postcode-finder.php', 
    data: formData, 
    dataType: 'json', 
    encode: true, 
    success: function (data) { 
     // do stuff 
    } 
}); 

docs

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

+0

谢谢你,我成功了:function(),现在它工作的很好:) – Goodbytes