简体   繁体   中英

How do I load the ajax data into a div with jquery?

I'm trying to do is load an external html page then display the contents within a div when a button is clicked.

I get the alert message displaying the contents of the test.html, however when I try to display it within a div nothing happens.

The contents is just a div tag. I don't want to load the div tag just the text itself which does come up in the alert message.

Within a html file, I know I don't really need to use ajax for something so simple however if I can get this to work it will help me with future problems.

      $.ajax({
      type: "GET",
      url: "test.html",
      dataType: "text",
      success : function(data) {
                    step1j = data;
            alert(step1j); // WORKS
            return step1j;
                }
    });


$("#step1").click(function() {
    $("#texter").html(step1j);
});

Ajax calls are asynchronous by default so what you have won't work. What I would suggest is using jQuery's .load() which handles the entire loading into a div for you (jQuery reference info here ).

$("#step1").click(function() {
    $("#texter").load("test.html");
});

For this to work, the following must be true:

  1. #step1 must exist already at the time you run this initial code (eg the DOM must already be loaded to install the .click() handler. For example, you can't install a click handler from code in the <head> tag because the page DOM has not yet loaded.
  2. #texter must exist at the time of the click. Please make sure there is no misspelling there.
  3. The URL you are loading must be of the same origin (eg same domain) as the web page where you are running the javascript. This is because of the brower's "same origin" security restrictions.

Read this answer if you want to learn more about why you can't return data from an asynchronous Ajax call like you were trying to do. Asynchronous calls finish some indeterminate time later and thus the only reliable place to use their results is in the completion callback or in a function that you call from within the completion callback. In this case, .load() is a higher level piece of jQuery functionality that makes this easier.

Try this:

$("#step1").click(function() {

    $.ajax({
      type: "GET",
      url: "test.html",
      dataType: "text",
      success : function(data) {
            $("#texter").html(data);
            //step1j = data;
            //alert(step1j); // WORKS
            //return step1j;
      }
});
});

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