2012-07-31 126 views
0

你好試圖用我的網頁上JSONP並生成以下使用JavaScript代碼:這是使用下面JSONP和401響應

function handleRefresh(url) { 
    console.log("here"); 

    var newScriptElement = document.createElement("script"); 
    newScriptElement.setAttribute("src", url); 
    newScriptElement.setAttribute("id", "jsonp"); 
    var oldScriptElement = document.getElementById("jsonp"); 
    var head = document.getElementsByTagName("head")[0]; 
    if (oldScriptElement == null) { 
     head.appendChild(newScriptElement); 
    } 
    else { 
     head.replaceChild(newScriptElement, oldScriptElement); 
    } 
} 

function updateStats(stats) { 
    var salesDiv = document.getElementById("stats"); 
    var newData = []; 
    if(!stats){ 
     alert("need to log in"); 
    }else{ 
     alert("ok"); 
    } 
    for (var s in stats) 
    { 
      var data = stats[s]; 
      data.language = s; 
      newData.push(data.language); 
     }  


    for (var i = 0; i < newData.length; i++) { 
     var glossa = newData[i]; 
     var stat = stats[glossa]; 

     var div = document.createElement("div"); 
     div.setAttribute("id", "progressbar"); 
     var indicator = document.createElement("label"); 
     indicator.setAttribute("id","indicator"); 

     var checkbox = document.createElement('input'); 
     checkbox.type = "checkbox"; 
     checkboxname = glossa; 
     checkbox.value = "value"; 
     checkbox.id = "id"; 

     glossesArray[i]=glossa; 

     div.appendChild(checkbox); 
     div.appendChild(indicator); 

     var zaab = parseInt(stat.completed, 10); 
      //console.log(zaab); 

     if(zaab < 35){ 
      indicator.innerHTML = glossa; 
     }else{ 
      indicator.innerHTML = glossa + " : " + stat.completed; 
      } 
     indicator.style.width = stat.completed; 
     //indicator.innerHTML = glossa + " : " + stat.completed; 

     if (salesDiv.childElementCount == 0) { 
      salesDiv.appendChild(div); 
     } 
     else { 
      salesDiv.insertBefore(div, salesDiv.firstChild); 
     } 

    } 
      //alert(zaab); 

    if (stats.length > 0) { 
     lastReportTime = stats[stats.length-1].time; 


    } 
} 

生成的代碼

<script src="https://{{ username }}:{{ password }}@www.link.com/api/2/project/link/resource/core/stats/?callback=updateStats&amp;random=1343727774180" id="jsonp"></script> 

的問題是,如果我在未得到未經授權的答覆(401)之前不登錄,那麼如何閱讀我收到的答覆?

回答

1

設置 '回調= updateStats'。現在添加到你的js功能

function updateStats(response){ 
// do something with response 
} 
+0

問題是,如果響應是401,它的功能永遠不會被調用!所以我不能在這裏做任何事情!如果我得到我的JSON數據,然後函數被調用正常! – 2012-07-31 10:32:21

+0

我也更新了我的答案,向您展示我的代碼! – 2012-07-31 10:34:18

+0

但你需要(如果401)過程響應?所以? – voodoo417 2012-07-31 10:39:05