开发者

Converting AJAX to jQuery

How would you convert following code to use only jquery library?

<开发者_如何学Go;html>
<head>
<script>
function do_it(value)
{
function newXMLHttpRequest()
{
   try{ return new XMLHttpRequest(); }catch(e){}
   try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
   try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
   return null;
}

var ajax_request = false;
ajax_request = newXMLHttpRequest();
var url = "test.pl?b64="+value;
    ajax_request.open("GET",url,1);
    ajax_request.onreadystatechange = function()
    {
        if(ajax_request.readyState == 4)
        {

            var response = ajax_request.responseText;
            document.getElementById("in").innerHTML = response;

        }
    }
    ajax_request.send(null);
}
</script>
</head>
<body>

<form>
<input type="text" name="string" onkeyup="do_it(this.value)"/>
<input type="submit" name="submit">
</form>
<div style="position:absolute;width:200px;height:200px; background-color:yellow; margin-top:100px;" id="in"></div>

</body>
</html>

Sorry, I probably should have mentioned that I don't actually have any practical experience with jquery, and I am in process in familiarizing myself with it now...


take a look at jquerys load() - i think thats what you're looking for:

function do_it(value){
  $('#in').load('test.pl', { b64: value });
}

EDIT: if you want to have different error- and success-handlers, using ajax() like others posted would be the way to go - but for qa simple get-this-and-put-it-into-that-div-request, load() is more short and easy.

EDIT2: to your comment: the best would be to to identify your input field in any way (give an id to it, or give the same class to every field that should get this event) and then simply do:

$('#mytextfield').keyup(function(){ // with id-selector
  do_it($(this).val());
});

$('.textfield').keyup(function(){ // with class-selector
  // whatever
});

(not: i havn't tested that, just writing out of my mind... if there's a problem, just take a look at the documentation)


$.ajax({
  url: 'test.pl?b64=' + value,
  success: function(data) {

      // document.getElementById("in").innerHTML = data; 

      $("#in").html(data);  // jQuery way instead of above line

  }
});

Note: not tested, but it shouldn't be too hard to figure out what this code is doing.


The most similar jQuery function would be $.Get.

$.get('test.pl?b64=' + value, function(data) {
  $('#in').html(data);
});


function getData(service, successFunction, failureFunction, getDataType) {
    $.ajax({
        type: 'get',
        cache: false,
        url: service,
        error: function(XMLHttpRequest, textStatus, errorThrown){
            failureFunction(XMLHttpRequest, textStatus, errorThrown);  //Pass error details to the failure function
        },
        success: function(data) {
            successFunction(data); //pass data to the success function
        },
        dataType: getDataType
    });
}

Something like that, where the service is the URL, the successFunction is the one you do something with the data, and the dataType is the expected type of data you will be receiving.

JQuery Docs

This might seem a little overwhelming, I'm sorry I tend to use closures so I only have one or two generic AJAX functions (GET and POST), for anyone interested here is a sample function calling the getData Function above

function getUserLabs()
{
    function successFunction(data){
        userLabs = new Array();
        $.each(data, function(i,item){
            var labID = data[i]['pk'];
            var labName = data[i]['fields']["name"];

            userLabs.push(new Array(labID, labName));
        });
    }

    function failureFunction(data) {
        alert("Data not received");
    }

    getData('lab/summary/', successFunction, failureFunction, 'json');
}


To help reduce code footprint, I prefer to use jQuery.post(). You can read more about it here http://api.jquery.com/jQuery.post/

Actually, you specified "GET" as your method, so the better option here is jQuery.get(). You can read more about it here http://api.jquery.com/jQuery.get/

Example:

$.get("test.pl", { b64: value },
    function(data){
         document.getElementById("in").innerHTML = data;
     });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜