简体   繁体   中英

jquery ajax call response in javascript is blank

The fail function gives me a correct output, whereas the done function gives me blank. I am stuck with this for hours. Any idea on how to debug this?

var xhr = false;

if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

if (contentType == null) {
    contentType = "application/json";
}

var reqst = $.ajax({
        beforeSend : function(req) {
          req.setRequestHeader("Content-Type", "application/json");
        },
        url : url,
        type : "post",
        contentType : contentType,
        data : paramsTable,
        });

reqst.done(function(xhr){
alert(xhr.responseText);
});

reqst.fail(function(xhr){
alert(xhr.responseText);
});

Try to use standard jquery ajax structure:

$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $( this ).addClass( "done" );
})
.fail(function() {
    alert( "error" );
});

I would like to recommend you to use Ajax jQuery API instead of the old Ajax requests. No body uses it today (almost nobody; since you use it)

$.ajax({
   beforeSend: function(req) {
     req.setRequestHeader("Content-Type", "application/json");
   },
   url: url,
   type: "post",
   contentType: contentType,
   data: paramsTable,
   success: function () {
     // here the code to execute if success
   },
   error: function () {
     // here the code to execute if error..
   }
});

Why your code isn't working

Because you are never using the xhr to send the Ajax request so it has nothing to show as the response text. Funny isn't it? hehehe.

use this:

success: function(resp) {
  alert(resp); // where resp is the name of the responseText here..
}

I have shown you how to use it. Good luck!

For more: http://api.jquery.com/jquery.ajax/

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