【发布时间】:2016-03-07 09:04:31
【问题描述】:
我尝试使用回调函数,但仍然没有效果。这是 HTML:
<form action="{% url 'seller_details' %}" method="post" id="seller_details">
{% csrf_token %}
<div>
<div class="heading">PERSONAL INFORMATION</div>
<table>
<tr>
<td id="wd25">Full Name</td>
<td><input type="text" placeholder="Full Name" name="full_name" value="{{full_name}}"/></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" placeholder="Mobile Number" value="{{mobile}}" name="mobile"/></td>
</tr>
<tr>
<td>Store Address</td>
<td><textarea rows="5" placeholder="Store Address" name="pickup_address" value="{{pickup_address}}"></textarea></td>
</tr>
</table>
</form>
然后我尝试验证表单并使用 jQuery validate 的 submit handler 提交表单
$("#seller_details").validate({
rules: {
full_name: "required",
pickup_address:"required",
},
messages: {
full_name: "Please enter Name",
mobile: "Please enter Mobile Number",
pickup_address:"Please enter address",
},
submitHandler: function(form){
var form = $(form).serialize()
codeLatLng(storeGeoAddress);
console.log(latitude)
console.log(longitude)
$.ajax({
type: "post",
url: "{% url 'seller_details' %}",
data: form + "&csrfmiddlewaretoken=" + '{{csrf_token}}' + '&latitude=' + latitude + '&longitude=' + longitude,
我使用了以下名为geocoder的异步函数来获取提交地址的纬度和经度
function codeLatLng(callback) {
var address = $("textarea[name=pickup_address]").val();
if (geocoder) {
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results[0]);
} else {
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
}
function storeGeoAddress(addr) {
latitude = addr.geometry.location.lat();
longitude = addr.geometry.location.lng();
}
我在这里面临的问题是我无法收集纬度和经度的值,以便我可以将其返回给我的提交处理程序,以便它可以发布这些值?在这种情况下我能做什么?谢谢
纬度和经度在此处全局定义
console.log(latitude) console.log(longitude) 无法记录任何内容
有什么方法可以让我提交处理程序作为我的回调函数?
【问题讨论】:
-
latitude和longitude变量的范围是什么?如果它们在这两个函数的范围内,那么你所拥有的应该可以工作,尽管在请求的查询字符串中放置一个 JSON 字符串是相当奇怪的。你最好只发送一个普通对象并让 jQuery 为你编码。 -
无论
latitude and longitude的范围如何,您所拥有的都不会起作用。$.ajax将在storeGeoAddress回调被触发之前运行,因为storeGeoAddress中的逻辑是异步的。您需要在回调中执行 AJAX。然后你也可以解雇讨厌的全局变量。 -
两个变量都是全局变量
-
那么在这种情况下提交处理程序应该是回调
-
我可以将提交处理程序作为回调吗?
标签: jquery google-maps asynchronous geocoding