开发者

How do I get a simple jQuery code to replace my current Javascript

开发者 https://www.devze.com 2023-03-16 20:07 出处:网络
Goal : When click a link on my navigation will show spinning image until script fully loaded. function ahah(url, target) {

Goal : When click a link on my navigation will show spinning image until script fully loaded.

function ahah(url, target) {
  document.getElementById(target).innerHTML = '<img src="loading.gif" />';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Mi开发者_如何学编程crosoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
    ahah(name,div);
    return false;
}

On Link

<a href="wrapper.html" onclick="load('file1.html','content');return false;">File 1</a>
<a href="wrapper.html" onclick="load('file2.html','content');return false;">File 2</a>

On content wrapper

<div id="content"></div>

Let me know simple way to do this on jquery.


Assuming each <a href="wrapper.html"> element corresponds sequentially to a file-n.html, you could do this:

$(function() {
    var content = $('#content');

    $('a[href="wrapper.html"]').each(function( i ) {
        var name = "file" + (i + 1) + '.html';

        $(this).click(function( e ) {
            e.preventDefault();
            content.html( '<img src="loading.gif" />' );
            $.ajax({
                url: name,
                dataType: 'html',
                success: function( data ) {
                    content.html( data );
                }, 
                error: function(xhr, status, error) {
                    content.html( "Error:\n" + status + "\n" + error;
                }
            });
        });
    });
});

Of course, don't forget to include the jQuery library first.


I think you only need to rewrite 'ahah'. Here is how I did it. I also omitted your 'ahahDone' callback and incorporated it into this implementation.`

function ahah(url, target) {
    $("#" + target).html('<img src="loading.gif" />');
    $.ajax({
        url: url,
        type: "GET",
        success: function (data, status, req) { $("#" + target).text(req.responseText); },
        error: function (req, status, err) { $("#" + target).text(" AHAH Error:\n" + req.status + "\n" + req.statusText); }
    });
}
0

精彩评论

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