ajax傳回值的問題的一個例子

來源:互聯網
上載者:User

這兩天偶然看到有人問ajax傳回值的問題,呵呵,恰巧我這幾天也在做這方面的一個東西。順便解決一下這問題

大家可以看看以下代碼

<html>
 <head>
  <title>ajax測試</title>
  <script>

// 產生xhr對象(相容各種瀏覽器)
   function createXHR()
   {
    var xhr;    
    
    try
    {
     xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
     try
     {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
     catch(e)
     {
      xhr = false;
     }
    }    
    if(!xhr && typeof XMLHttpRequest != 'undefined') xhr = new XMLHttpRequest();
    
    return xhr;
   }
   

// 得到要顯示的ajax的取值(ie)
   function ieShow(geturl)
   {
    var xhr; 
    xhr = createXHR();
    var returnStr = '';
    xhr.open("GET", geturl);
    
    xhr.onreadystatechange = function()
    {
     if(xhr.readyState == 4 && xhr.status == 200)
      returnStr = xhr.responseText;
    }
    
    xhr.send(null);       //alert('');
    return returnStr;
   }

   // 在指定塊中顯示字元
   function showStr(str)
   {
    document.getElementById('show').innerHTML = str;
   }
   

//  在網頁中顯示ajax的取值(ie)
   function ieEnableShow(geturl)
   {
    var str = ieShow(geturl);
    showStr(str);
   }
   

// 相容ff ie的方式
   function FFIEShow(geturl, funName)
   {
    var xhr; 
    xhr = createXHR();
    var returnStr = '';
    xhr.open("GET", geturl);
    
    xhr.onreadystatechange = function()
    {
     if(xhr.readyState == 4 && xhr.status == 200)
      funName(xhr.responseText);
    }
    
    xhr.send(null);
   }
  </script>
 </head>
 <body>
  <input type='button' value='ie顯示結果' onclick='ieEnableShow("ajaxshow.php",);'>
  <input type='button' value='firefox ie都顯示結果' onclick='FFIEShow("ajaxshow.php", showStr);'>
  <div id='show'></div>
 </body>
</html>

'ajaxshow.php'檔案的內容

<?php
echo '1,2,3,4';
?>

我是用php如果你用其它語言你可以自己改一下,很簡單就是在網頁中列印字串'1,2,3,4'。

從以上代碼中可以看出ie可以利用return來得到值。但firefox則不能,只能在readyState == 4 && status == 200時處理一個函數這個函數應當作為一個參數傳遞入函數。有個奇怪現象你如果去除紅線部分的注釋,firefox又可以取到值。估計是firefox使用ajax取值有個延時造成。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.