jQuery load content from link with Ajax

后端 未结 4 1130
[愿得一人]
[愿得一人] 2020-12-15 15:08

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

4条回答
  •  我在风中等你
    2020-12-15 15:37

    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.

    
    

    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);
          }
        });
        });
    
    });
    

提交回复
热议问题