简体   繁体   中英

jQuery load content from link with Ajax

I have a -link element that has href link to page, but I have to use Ajax to load that content from href -url and not redirect user to that page. How can I modify my link to just load content from that link, so I can inject that content to current page?

<a class="bind-jquery-event-here-class" href="http://webpage.com">Link</a>

I made this, but it doesn't work.

$(".bind-jquery-event-here-class").bind("click", function() {       
    var url = $(this)attr("href").val();
    var content = $.load(url);
    alert(content);
});

The load function is not intended to gather the request response, this function is used to load HTML from a remote file and inject it to a DOM element, for example:

$('a').bind('click', function(e) {           
  var url = $(this).attr('href');
  $('div#container').load(url); // load the html response into a DOM element
  e.preventDefault(); // stop the browser from following the link
});

If you handle click events of anchor elements you should prevent the browser from following the link href.

Also keep in mind that Ajax request can be done only withing the same domain due the Same Origin Policy .

There are several problems with your code:

1) you did not specify the argument of your anonymous function. the argument is the event (here: the click). you'll be needing this later to disable the 'normal' behaviour of the click:

   $("a.bind-jquery-event-here-class").bind("click", function(event) {
       event.preventDefault();

2) For reading the href you don't need val() . ( val() is for reading stuff from input-fields.)

   var url = $(this).attr("href");

3) the A in AJAX stands for asynchronous. for your code this means: load just starts the loading of data from the server, but doesn't wait until it finishes. you have to define a callback-function that handles the data when it finally arrives.

4) load is for doing an AJAX call and inserting the result into the DOM. you can't use it for an alert. use $.ajax instead if you relly need an alert.

5) you can't load abitrary URLs via AJAX, your AJAX call can only go back to your own server. if you need to load stuff from other server you have to use a serverside script as a proxy. here's how you call the proxy:

    $.ajax({
       type: "POST",
       url: "proxy.php",
       data: "url="+url, 
       success: function(data){
           alert("finally got data " + data);
       }
     });

and here's an example proxy in php.

<?php
error_reporting (E_ALL ^ E_NOTICE);
if ( isSet($_POST['url']) ) {
  if( true == ($str=file_get_contents( $_POST['url'] ) )) {
    echo $str;
    exit;
  }
} 
echo "could not read page"; 
?>

a word of warning regarding the php: file_get_contents might be disabled on your server.

An here's the complete javascript-code is used for testing:

  $(document).ready(function(){

    $("a.bind-jquery-event-here-class").bind("click", function(event) {
    event.preventDefault();
    var url = $(this).attr("href");
        alert("loading via proxy: " + url);
    $.ajax({
      type: "POST",
      url: "proxy.php",
      data: "url="+url, 
      success: function(data){
        alert("finally got data " + data);
      }
    });
    });

});

IF you have a whole menu with such a href links you can do this by selecting each child element in the menu container div attach a onclick event on it

$('#Menu >*').each(function(){<br>
        $(this).bind('click',function(e){<br>
            var el = e.target<br>
            if(el.nodeName ==="A"){<br>
                fireMenuLink(el.href);<br>
            }<br>
            return false;<br>
        });<br>
    });



You should always return false in jQuery to suppress the default behaviour of the tag

function fireMenuLink(){<br>
$("#container_element_ID").load(url,function(){<br>
//Do something like hide the loader<br>
        $('loaderStatus').hide();<br>
    });<br>
}



This comes in handy if you want to develop a screen which has support from server side and u want to load screen content dynamically while managing the browser history using the fragment URL. There are many libraries which you can use to manage screen content using fragment URL across browsers. Both in jQuery and other wise.

Hope this helps
Cheers :)

@bjelli is kinda right. But you might want to have your e.preventDefault(); before your AJAX call or everything else you wanted to do in the first place, because you really don't want a clients old and slow browser to even try to load the initialy requested resource.

Even though some programming languages can do some magic, most scripts work from the top to the bottom of your very script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM