开发者

check ajax have successful appended the html with jquery

helo im trying to check if a html is appended to a id, im not sure about the best way to do this in javascript, heres a snippet what i have made so far

var appendstatus= 0;

$.ajax({
    type: "GET",
    url: params['content'],
    dataType: 'text',
    success: function(data) {
        // append the html开发者_JAVA百科
        $(params["id"]).append(data);
        // is this the right way to check it ?
        appendstatus= 1;
    }
});

// got an 0, so its not global? 
console.log(appendstatus);
// do some jobs after the html is appended on the div id

the question is what is the best way to check some data is appended in this case ?

thanks for helping out

Adam Ramadhan


Because your AJAX request is asynchronous, the console.log() happens before the response is received.

Any code that relies on the successful response must be placed in (or invoked from) the success: callback.

Order of execution:

   // STEP 1: declare and initialize the variable
var appendstatus= 0;

  // STEP 2: send the asynchronous request
$.ajax({
    type: "GET",
    url: params['content'],
    dataType: 'text',
    success: function(data) {

           // STEP 4: The response was received, so this code runs.
        $(params["id"]).append(data);

        appendstatus= 1;

        console.log( 'appendstatus from callback:', appendstatus );
    }
});

  // STEP 3: log to the console, because we're not waiting for the response
console.log(appendstatus);


The success is a callback function which is run when the ajax operation is successfull. The rest of the code just runs and the callback function will idle till the success is received.

To check if the html was added, you can use simply:

alert($(params["id"]).append(data).html());

This will alert you the html code in that element. You may also use just console.log ofcourse.


If the success function is being called, it means the AJAX request was succesfull and you got the data.

At this point you can check the data to see if it contains what you did expect to receive.

After that point, you are relying on some pretty safe functions, finding an element by ID and use the jQuery append method, so at most you may want to check jQuery found the right element via the ID passed... then you should be pretty sure the data has been appended.

Since that data contains DOM nodes (you are appending them), you can check if you find those elements using a jQuery function again, but that is paranoia to me :D.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜