我通过Ajax将一些数据发送到PHP脚本。 PHP脚本检查是否有正确的$ _SESSION。如果没有会话,将显示一个模式以让用户登录。到目前为止一直很好......
不,我想要,登录数据后应再发送一次。这是代码:
$(document).on('click', '#button', function(e) {
var content = $('#anything').val();
var id = $('#anything').attr('data-id');
var data = { 'id': id, 'content': content };
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.response) {
// Everything is fine, so do something with the data
}
else {
modal(login);
// Showing modal for login. After login repeat the AJAX
}
});
});
如果用户未登录,则会创建一个表单并显示为模式:
function modal(type) {
if ( !$('#modal').length ) {
if (type == "login") {
$('body').prepend('<div id="modal"><h1>Login</h1><form id="loginform"><input type="text" name="username" class="input login_input" id="username"><input type="password" name="password" class="input login_input" id="password"><button type="submit">Login</button></form></div>');
}
}
}
现在用户可以登录:
$(document).on('submit','#loginform',function(event){
var username = $('#username').val();
var password = $('#password').val();
$.ajax({ url: "login.php", type: "POST", data: { 'username': username, 'password': password }, dataType: "json" })
.done(function( json ) {
// User is now logged in -> Repeat sending first data
});
});
但是在此登录之后,应该再次发送第一个数据以完成第一个用户请求。我怎么能这样做?
答案 0 :(得分:2)
你可以编写调用第一个ajax作为单独函数的函数,可以从dom ready和第二个ajax调用
function initiate() {
var content = $('#anything').val();
var id = $('#anything').attr('data-id');
var data = {
'id': id,
'content': content
};
$.ajax({
url: "script.php",
type: "POST",
data: data,
dataType: "json"
}).done(function (json) {
if (json.response) {
// Everything is fine, so do something with the data
} else {
modal('login');
// Showing modal for login. After login repeat the AJAX
}
});
}
$(document).on('click', '#button', initiate);
function modal(type) {
if (!$('#modal ').length) {
if (type == "login") {
$('body ').prepend(' < div id = "modal" > < h1 > Login < /h1><form id="loginform"><input type="text" name="username" class="input login_input" id="username"><input type="password" name="password" class="input login_input" id="password"><button type="submit">Login</button > < /form></div > ');
}
}
}
$(document).on('submit ', '#loginform ', function (event) {
var username = $('#username ').val();
var password = $('#password ').val();
$.ajax({
url: "login.php",
type: "POST",
data: {
'username': username,
'password': password
},
dataType: "json"
}).done(function (json) {
// User is now logged in -> Repeat sending first data
initiate();
});
});