2011-11-20 18 views
0

我打算用XMLHttpRequest調用一個PHP文件,但現在調用沒有完成,我不知道爲什麼。 req.readyState不是4,我不知道爲什麼,因爲PHP文件沒問題,並且確實如此(只是回顯一個字符串)。XMLHttpRequest Dosen't complete

任何人都可以看到我看不到?

function processAjax(id, option) { 
    if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id; 
    else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id; 

    //create AJAX request 
    if (window.XMLHttpRequest) { // Non-IE browsers 
     req = new XMLHttpRequest(); 
     req.onreadystatechange = targetDiv(); 
     try { 
      req.open("GET", url, true); 
     } catch (e) { 
      alert(e); 
     } 
     req.send(null); 
    } else if (window.ActiveXObject) { // IE 
     req = new ActiveXObject("Microsoft.XMLHTTP"); 
     if (req) { 
      req.onreadystatechange = targetDiv(); 
      req.open("GET", url, true); 
      req.send(); 
     } 
    } 
} 
//this function handles the response from the ajax request 

function targetDiv() { 
    if (req.readyState == 4) { // Complete 
     if (req.status == 200) { // OK response 
      //all of the code below doesn't happen because its not the option 
      if (option == "lpath") { 
       var response = req.responseText.split('##'); 
       var articles = response[0].split(';'); 
       var quizes = response[1].split(';'); 

       document.getElementById("article_id").innerHTML = ""; 
       document.getElementById("quiz_id").innerHTML = ""; 

       for (var i = 0; i < articles.length; i = i + 2) { 
        if ((i + 1) <= articles.length) { 
         var option = new Option(/* Label */ articles[i + 1], /* Value */ articles[i]); 
         document.getElementById("article_id").options.add(option); 
        } 
       } 

       for (var i = 0; i < quizes.length; i = i + 2) { 
        if ((i + 1) <= quizes.length) { 
         var option = new Option(/* Label */ quizes[i + 1], /* Value */ quizes[i]); 
         document.getElementById("quiz_id").options.add(option); 
        } 
       } 

       delete req, articles, quizes; 
      } else { 
       document.getElementById("catdiv").innerHTML += req.responseText; 
       document.getElementById("allchildren").value = req.responseText; 
      } 
     } else { //failed to get response 
      alert("Problem: " + req.statusText); 
     } 
    } 
    document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!"; 
} 
+0

它是跨域嗎? –

+0

是'<?php echo $ mosConfig_live_site;?>'HTML源代碼的一部分,還是PHP源代碼?如果它是HTML源代碼的一部分,你的PHP不會被解釋... – mc10

+0

不,它不是跨域和mc10我檢查和url輸出正常。這一切來源都是PHP源代碼。 –

回答

3
req.onreadystatechange = targetDiv(); 

應該

req.onreadystatechange = targetDiv; 

原代碼調用的代碼行運行後立即targetDiv(),這可能不是你想要做什麼。固定代碼在收到Ajax請求後正確調用該函數。

+0

如果我想要targetDiv函數來recive一個參數,我該怎麼做?雖然它的工作非常感謝人! –

+0

您無法將自己的參數傳遞給函數。 'onreadystatechange'會自動傳遞事件對象,你可以通過'function targetDiv(event){'(現在你可以在你的函數中使用'event')來訪問它,但是其他參數不能被傳遞。 – mc10

+0

再次感謝男人 –