简体   繁体   中英

How to use $.ajax() function to get URL from a search bar and display the HTML response in a DIV

HTML:

    <div id="browse-container">
      <input type="search" id="search-bar" placeholder="Search URL..."></input>

      <button id="search-button">Search</button>
    </div>

Above I have a search input where the user should be able to type in any URL.

Script:

    $('#search-button').click(function(){
      var HTMLresp = $('#search-bar').val();

      $.ajax({
          url: HTMLresp,
          dataType: "jsonp",
          type: 'GET'
      });
            $('body').append('<div id="result-window"></div>');        
            $("#result-window").html(HTMLresp); 
    });

Now when the user clicks on the button the specified url is to be placed in a variable 'HTMLresp' and then that URL should be placed inside of the ajax function. After ajax function is done the HTML response of the specified URL should be displayed in a the result window div on the page.

But right now the page just displays the string version of the URL.

JsFiddle

Try as follows:

$('#search-button').click(function(){
  var HTMLresp = $('#search-bar').val();
  $('body').append('<div id="result-window"></div>'); 
  $.ajax({
      url: HTMLresp,
      dataType: "jsonp",
      type: 'GET',
      success: function(data) {
          $("#result-window").html(data);
      }
  });
});

This way, when your request finishes, and is succesfull, the response data will be placed inside your div. You should put an error handler as well, this is just a rough example.

Keep in mind the following line:

$('body').append('<div id="result-window"></div>');

This will be executed each time the user clicks the #search-button element, You should place the div #result-window directly in your dom, or append it on document load, otherwise you will end up having a lot of divs with id #result-window

I also recommend you to read about CORS and JSONP a little, because what you want to do as a lot of limitations, you cannot ask for resources from different domains (You can, with jsonp as you do, but it has its limitations as well).

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

http://en.wikipedia.org/wiki/JSONP

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