this.submit is not triggering GET call

限于喜欢 提交于 2019-12-25 18:17:28

问题


Why isn't the call

this.submit()

not triggering a submit and calling my controller? The dev tools in Chrome says there is an error and that the function doesn't exist!

$('form').submit(function(e) {
    e.preventDefault();
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('SearchQuery').value;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("Location found: " + results[0].geometry.location);
            $(this).submit();

        }
        else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
});

@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<div class="form-group">
  @Html.TextBoxFor(model => model.SearchQuery, new { @class = "form-control"}) @Html.ValidationMessageFor(model => model.SearchQuery, "", new { @class = "text-danger" }) @Html.ValidationMessageFor(model => model.Longitude, "", new { @class = "text-danger"
  }) @Html.TextBoxFor(model => model.ClassDate, "{0:MM/dd/yyyy}", new { @class = "datefield form-control" }) @Html.ValidationMessageFor(model => model.ClassDate, "", new { @class = "text-danger" }) @Html.Hidden("latitude", Model.Latitude) @Html.Hidden("longitude",
  Model.Longitude)
</div>
<button type="submit" id="submitSearch" class="btn btn-default">Search</button>
}

回答1:


Firstly $(this).submit() is not referring to your form. Your inside another function associated with geocoder so your trying to call the .submit() function of geocoder which does not exist.

Even if you saved the form element to a variable, it would create an endless loop. Inside that function you first cancel the submit. Then your call the function again, cancel it again, call the function again, cancel it again, and so on and so on until the browser spits the dummy.

Instead, perform your logic first, then if you want to prevent the form submitting, cancel it (and if you don't cancel it, it will do a normal submit)

$('form').submit(function() {
  var geocoder = new google.maps.Geocoder();
  var address = $('#SearchQuery').val();
  var caSubmit = true; // assume we can
  geocoder.geocode({ 'address': address }, function (results, status) {
    if (status != google.maps.GeocoderStatus.OK) {
      canSubmit = false; // signal we should not submit
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
  return canSubmit; // if its false, the submit will be cancelled
});


来源:https://stackoverflow.com/questions/31977951/this-submit-is-not-triggering-get-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!