我有一个用于在 MVC3 应用程序中搜索的对话框。对话框上的搜索按钮发布到 MVC3 Controller 操作,该操作返回搜索结果的 JSON,然后将其解析为 HTML 表。当用户单击对话框上的“搜索”按钮时,所有这些都可以正常工作。
但是,在某些情况下,我希望对话框打开后自动开始搜索。不幸的是,这不起作用。用户必须实际单击“搜索”按钮才能启动搜索。
我的代码如下所示:
$('#RepSearchDialog').dialog({
autoOpen: true,
width: 1050,
height: 500,
resizable: false,
title: 'Rep Search',
modal: true,
open: function () {
$('.ui-dialog-titlebar').hide();
$('#RepSearchStoreId').val($('#StoreId').val());
// This part doesn't work, not sure why
//RepSearchDialog_SearchForReps();
}
});
搜索按钮有这样的JS:
$('#RepSearchButton').click(function (e) {
RepSearchDialog_SearchForReps();
});
RepSearchDialog_SearchForReps 看起来像这样:
function RepSearchDialog_SearchForReps() {
$('#RepSearchForm').submit(function () {
$.ajax({
url: this.action,
type: "POST",
cache: false,
dataType: 'text json',
data: $(this).serialize(),
success: RepSearchDialog_SearchForRepsComplete,
error: function (request, status, error) {
alert("An error occurred submitting the form. \r\n\r\n Error: " + request.responseText);
}
});
return false;
});
}
function RepSearchDialog_SearchForRepsComplete(response, status, xhr) {
$('#RepSearchButton').unbind(); // NECESSARY, or you will get stacked calls!!
if (status == "error") {
alert('failed');
}
else {
LoadRepSearchResults(response);
}
}
RepSearchDialog_SearchForReps 调用只是对 MVC3 Controller 进行 AJAX 调用,并将返回值附加到对话框内托管的 DIV 中的 HTML 表中。当用户单击“搜索”按钮时,所有这些都会起作用。但尝试在 OPEN 函数中自动启动此功能却不会。有什么线索吗?
最佳答案
您的搜索按钮起作用的原因是它仍然使用正常的帖子以及调用您的 JavaScript。您需要将其更改为:
$('#RepSearchButton').click(function (e) {
e.preventDefault();
RepSearchDialog_SearchForReps();
});
这里的e.preventDefault()
将阻止 native 提交事件的发生。
另一个问题是您的 RepSearchDialog_SearchForReps。按照您的设置方式,您将 $.ajax 调用绑定(bind)到 submit每次调用 RepSearchDialog_SearchForReps 时都会发生事件。为此,您有两种选择。您可以简单地执行以下操作:
function RepSearchDialog_SearchForReps() {
var form = $('#RepSearchForm');
$.ajax({
url: form.attr('action'),
type: "POST",
cache: false,
dataType: 'text json',
data: form.serialize(),
success: RepSearchDialog_SearchForRepsComplete,
error: function (request, status, error) {
alert("An error occurred submitting the form. \r\n\r\n Error: " + request.responseText);
}
});
}
或者这个
// this goes in your document ready code elsewhere...
$(function() {
$('#RepSearchForm').submit(function () {
$.ajax({
url: this.action,
type: "POST",
cache: false,
dataType: 'text json',
data: $(this).serialize(),
success: RepSearchDialog_SearchForRepsComplete,
error: function (request, status, error) {
alert("An error occurred submitting the form. \r\n\r\n Error: " + request.responseText);
}
});
return false;
});
});
function RepSearchDialog_SearchForReps() {
$('#RepSearchForm').submit();
}
关于ajax - MVC3 和 JQuery 对话框打开对话框时不会提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8345471/