为什么jQuery ajax运行两次?
问题描述:
我已阅读所有的答案,他们似乎涉及事件处理程序,这与我的情况并非如此。为什么jQuery ajax运行两次?
JS
$(function() {
var data = {};
data.action = "getUser"
ajax('post', 'php/login.php', data, success, "Initialization error: ", 'json', false);
function success(result) {
if (result) {
var data = {};
window.localStorage.setItem("user-id", result.userid);
console.log("userid=" + result.userid);
console.log("username=" + result.username);
console.log("user-id from storage=" + window.localStorage.getItem("user-id"));
} else {
var msg = "Welcome to the Writer's Tryst. Create an account to participate as a writer or enabler.";
showMessage(1, msg);
console.log(msg);
}
}
})
function formatError(errmsg, err, xhrmsg) {
return errmsg + (err.length ? err + " " : '') + (xhrmsg.length ? xhrmsg : '');
}
function ajax(method, url, data, success_callback, errmsg, dataType, cache, processData, contentType) {
cache = typeof cache !== 'undefined' ? false : true;
processData = typeof processData !== 'undefined' ? false : true;
contentType = typeof contentType !== 'undefined' ? false : "application/x-www-form-urlencoded; charset=UTF-8";
dataType = typeof dataType !== 'undefined' ? dataType: 'text';
$.ajax({
type: method,
url: url,
data: data,
cache: cache,
processData: processData,
contentType: contentType,
dataType: dataType
}).done(function (result, success, xhr) {
success_callback(result);
}).fail(function (xhr, desc, err) {
var msg = formatError((errmsg ? errmsg : ""), err, xhr.responseText);
showMessage(0, msg);
console.log(msg);
});
}
function showMessage(errorType, msg) {
switch (errorType) {
case 0:
$("#message").text(msg).css({ 'color': 'white', 'background-color': 'red', 'display': 'block' });
break;
case 1:
$("#message").text(msg).css({ 'color': 'white', 'background-color': 'green', 'display': 'block' });
break;
default:
$("#message").text(msg).css({ 'color': 'white', 'background-color': 'orange', 'display': 'block' });
break;
}
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
$(document).on("keypress click", function(){$("#message").css({'display': 'none'})})
的console.log
用户ID = 52的用户名从存储=外前的userid = 52
用户ID = 52的用户名=外前用户id from storage = 52
答
因为有两个控制台条目,它在发送两次后看起来有问题,但是当您检查网络选项卡时,只有一个请求。
尝试进入网络选项卡,使用左上角的红色圆圈/斜线按钮清除所有内容,然后再次触发请求,看看是否有两个条目出现。
为什么函数成功(结果){'在DOM准备好处理程序? –
不管它是否是因为它传递给ajax函数 – nuway