2012-01-17 44 views
0

人們向我推薦我應該將此代碼轉換爲jquery,但是如何以及在哪裏,是否有任何工具或者如何執行此操作以及爲什麼XMLHttpRequest不適合jQuery?如何將普通JavaScript代碼轉換爲jQuery

我有這樣的代碼:

function showVal(str) { 
    if (str == "") { 
    document.getElementById("txtHint").innerHTML = "* Please type in School Name."; 
    return; 
    } 

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp = new XMLHttpRequest(); 
    } else {// code for IE6, IE5 
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange = function() { 
    if (xmlhttp.readyState == 4) { 
     if (xmlhttp.status == 200) { // break this into 2 statements so you can handle HTTP errors 
     document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
     } else { 
     document.getElementById("txtHint").innerHTML = "AJAX Error (HTTP "+xmlhttp.status+")"; 
     } 
    } 
    }; // functions declared in this way should be followed by a semi colon, since the function declaration is actually a statement. 

    // encodeURIComponent() does all the escaping work for you - it is roughly analogous to PHP's urlencode() 

    // xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true); 
    xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true); 

    xmlhttp.send(); 
} 
+2

你應該瞭解jQuery的一些文檔開始。從官方網站開始http://docs.jquery.com/How_jQuery_Works – 2012-01-17 17:09:46

+1

如果有效,可能沒有任何理由需要切換。事實上,如果您現在不使用(並加載)jQuery,那麼轉換爲jQuery只會增加頁面的大小。 – 2012-01-17 17:10:06

+0

它不適用於我的其他jQuery代碼:S – Drazek 2012-01-17 17:12:39

回答

2

如果你真的想要,轉換會使你的代碼更加緊湊...但具有jQuery的依賴的附加處罰。就個人而言,如果您願意爲這個相對簡單的功能處理跨瀏覽器問題,我沒有理由將其轉換。

話雖這麼說,這將會是比較容易的轉換:

function showVal(str){ 
    if(str == ''){ 
     $('#txtHint').html("* Please type in School Name."); 
     return; 
    } 

    $.get({ 
     url: 'ajaxFuncs2.php?q='+encodeURIComponent(str), 
     success: function(data){ $('#txtHint').html(data); }, 
     error: function(){ $('#txtHint').html('AJAX Error'); } 
    }); 
} 

...點左右

+0

不起作用:S – Drazek 2012-01-17 17:31:10

+0

@Drazek - 它至少應該足以讓你開始朝正確的方向發展。在不知道任何要求的情況下,我無法爲您編寫代碼。 – 2012-01-17 17:33:44

0

你可以使用它重寫jQuery's AJAX engine。這應該是一件容易的事。

但是你必須問自己一個古老的問題:我應該修補什麼不壞?

使用$.ajax它應該是這樣的:

function showVal(str){ 
    if(str == null || str == ''){ 
     $('#txtHint').html('* Please type in School Name.'); 
    } 
    else { 
     $.ajax({ 
       url: 'ajaxFuncs2.php?q='+encodeURIComponent(str), 
       success: function(data, textStatus, jqXHR){ $('#txtHint').html(data); }, 
       error: function(request, status, error){ $('#txtHint').html('AJAX Error (HTTP ' + status + ')'); } 
      }); 
    } 
} 
+0

使用jQuery可以使生活更輕鬆一些,因爲你可以看到代碼的作用,而不是所有的瀏覽器細節。 – 2012-01-17 17:17:22

+0

它不起作用,以及它如何可以很容易的任務,當我沒有javascript的知識 – Drazek 2012-01-17 17:17:43

+0

@Drazek好...你需要一些基本的JavaScript知識來編程JavaScript。但有很多資源(如http://www.w3schools.com/jquery/default.asp和http://www.w3schools.com/js/default.asp)。請稍微閱讀一下。 – 2012-01-17 17:20:03

相關問題