我正在实现一个表单,该表单请求使用ajax同步2个数据库的进程,我需要等到该进程完成。
在我的表单中,我有流动的代码来发送数据库凭据:
<div class="col-lg-offset-1 col-lg-11">
<?=
Html::a('Sync Databases', ['runsync'], [
'class' => 'btn btn-primary',
'id' => 'ajax_link_02',
'data-on-done' => 'linkFormDone',
'data-form-id' => 'syncdb_form',]
)
?>
我也用ajax注册了js
function handleAjaxLink(e) {
e.preventDefault();
var
$link = $(e.target),
callUrl = $link.attr('href'),
formId = $link.data('formId'),
onDone = $link.data('onDone'),
onFail = $link.data('onFail'),
onAlways = $link.data('onAlways'),
ajaxRequest;
$("#show_msg").html("Loading.... please wait...");
ajaxRequest = $.ajax({
type: "post",
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
// Assign done handler
if (typeof onDone === "string" && ajaxCallbacks.hasOwnProperty(onDone)) {
ajaxRequest.done(ajaxCallbacks[onDone]);
}
// Assign fail handler
if (typeof onFail === "string" && ajaxCallbacks.hasOwnProperty(onFail)) {
ajaxRequest.fail(ajaxCallbacks[onFail]);
}
// Assign always handler
if (typeof onAlways === "string" && ajaxCallbacks.hasOwnProperty(onAlways)) {
ajaxRequest.always(ajaxCallbacks[onAlways]);
}
}
var ajaxCallbacks = {
'linkFormDone': function (response) {
$('#show_msg').html(response.body);
}
}
ajax调用正常并调用控制器:
public function actionRunsync() {
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new \app\modules\admin\models\syncdb();
$response = $model->runSyncDb($_POST);
$res = array(
'body' => $response,
'success' => true,
);
return $res;
}
}
但不是在等待这个过程
$model->runSyncDb($_POST)
完成。如果我评论过程并添加文本,它可以正常工作,但如果过程需要很长时间则不行。
我做错了什么?
答案 0 :(得分:0)
我刚刚在ajax请求中添加了async false:
async: false,
所以现在ajax是这样的:
ajaxRequest = $.ajax({
type: "post",
async: false,
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
不确定最佳方式,但完美运作......