如何使用jquery从异步调用返回?

问题描述 投票:0回答:3

我尝试使用回调函数,但仍然无效。这是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();
}

我在这里面临的问题是我无法收集纬度和经度的值,因此无法将其返回给我的提交处理程序,以便它可以发布这些值?在这种情况下我该怎么办?谢谢

LatitudeLongitude在此处全局定义]

console.log(纬度)console.log(经度)无法记录任何内容

我可以通过什么方式使Submit Handler作为回调函数?

jquery google-maps asynchronous geocoding
3个回答
2
投票

应允营救。


2
投票

您正处于回调地狱!这是javascript中一个相当普遍的问题。从异步调用“同步”返回的方式是通过Promise。要么,要么您必须传递一系列回调以处理必须发生的各个步骤。


1
投票

您仍然可以在SubmitHandler内创建回调。>

codeLatLng(function(addr){
    var latitude = addr.geometry.location.lat();
    var longitude = addr.geometry.location.lng();

    console.log(latitude)
    console.log(longitude)

    $.ajax(...);
});
© www.soinside.com 2019 - 2024. All rights reserved.