2012-01-17 85 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