2016-05-17 137 views
0

我已閱讀所有的答案,他們似乎涉及事件處理程序,這與我的情況並非如此。爲什麼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

+0

爲什麼函數成功(結果){'在DOM準備好處理程序? –

+0

不管它是否是因爲它傳遞給ajax函數 – nuway

回答

0

因爲有兩個控制檯條目,它在發送兩次後看起來有問題,但是當您檢查網絡選項卡時,只有一個請求。

嘗試進入網絡選項卡,使用左上角的紅色圓圈/斜線按鈕清除所有內容,然後再次觸發請求,看看是否有兩個條目出現。