我正在使用ASP.NET上用Bootstrap 4 / JQuery / AJAX构建的应用程序。每当在页面上触发AJAX请求(单击按钮)时,在请求进行过程中页面会变成白色/空白,一旦完成AJAX请求,页面就会返回。结果数据也会成功填充。
我检查了stackoverflow的所有解决方案。大多数建议与将HTML页面上的任何按钮更改为type =“ button”有关。我也尝试过在按钮点击时设置event.preventDefault()
和event.stopPropagation()
。
我在div上使用了引导按钮。页面中有HTML表单,但我没有提交。
请在下面的示例代码中查找以供参考。
JS
$('#btnAuthenticate').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var url = resolveUrl('~/req/getData');
$.ajax({
type: "POST",
url: url,
data: {u:"",p:""},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
//gets the data here and populates it on a dropdown
//data is received successfully
},
error: function (response) {
alert("Error occurred while processing the request : " +response.d);
}
});
});
HTML
<div class="my-4">
<form>
<div class="form-row mx-1">
<div class="col-lg-12">
<div class="card mb-4">
<div class="card-header h3 font-weight-lighter">
<div class="float-left"><span class="h3 mr-2" data-feather="file"></span>Select</div>
<div class="float-right">
<button type="button" class="btn btn-sm btn-secondary float-right mr-1" data-toggle="modal" data-target="#exampleModalCenter" id="btnDownloadInit">
<span data-feather="download"></span> Download
</button>
</div>
</div>
</div>
</div>
</div>
</form>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Download</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="border border-gray rounded p-4">
<div class="row">
<div class="col-lg-12">
<label for="txturl">URL</label>
<input type="text" class="form-control" id="txturl" placeholder="URL here.." required/>
</div>
</div>
<div class="row mt-2">
<div class="col-lg-6">
<label for="txtUsername">Username</label>
<input type="text" class="form-control" id="txtUsername" placeholder="name" required/>
</div>
<div class="col-lg-6">
<label for="txtPassword">Password</label>
<input type="password" class="form-control" id="txtPassword" placeholder="" required/>
</div>
</div>
<div class="row">
<div class="col-lg-12 mt-4 mb-2">
<div class="btn btn-primary rounded" id="btnAuthenticate"><span class="mr-1" data-feather="lock"></span>Authenticate</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
CS
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
try
{
ConnectionDetails data = getConnectionDetails();
return JsonConvert.SerializeObject(data);
}
catch (Exception ex)
{
Logger.log.Error(ex);
HttpContext.Current.Response.StatusCode = 400;
throw new Exception("Error occurred");
}
}