从$ .ajax到javascript XMLHttpRequest的端口?

时间:2012-07-09 21:22:56

标签: javascript jquery ajax

寻找一些帮助,使用XMLHttpRequest将以下内容从jquery ajax转换为javascript?

$.ajax({
    url: 'api/dev/blah?id=4F',        
    type: 'GET',
    beforeSend: function(req) {
        req.setRequestHeader("Accept", "application/xml");
    },
    success: function (result) {
        alert('success');
        // Parse xml here...
    },
    error: function() { 
        alert('error');
}
});

我尝试过类似的东西,但我看不到fiddler发送的请求,暗示没有回复或错误(不是xmlhttprequest精明):

function junk() {
  var request = new XMLHttpRequest();
   request.addEventListener('load', successCallback, false);

   request.open("GET", 'api/dev/blah?id=4F', true);
   request.setRequestHeader("Accept","application/xml");
   request.setRequestHeader("Content-Type", "application/xml");
   request.send();
}

function successCallback(data) {
  alert('success');
}

3 个答案:

答案 0 :(得分:1)

试试这个

 request.onreadystatechange = callBackfunction();
 request.send(null);

.....

 function callBackfunction()
 {

  if(request.readyState == 4)   
  {
     //alert(request.responseText)
     if(request.status == 200)
      {     
          var xmlDoc = request.responseXML;
      var root = xmlDoc.documentElement;
      var nodesList = root.childNodes; 
      nodeListLen = nodesList.length;

    }// end of if(xmlRequest.status==200)

   } // end of if(xmlRequest.readyState==4)

  } // end of callBackfunction

答案 1 :(得分:1)

问题是XHR没有响应加载事件。它以onreadystatechange

回复
request.onreadystatechange = function(){
    if (request.readyState == 4 && (request.status >= 200 && request.status < 300)) {
        successCallback();
    }
}

答案 2 :(得分:1)

来自Eloquent JavaScript - chapter 14

function makeHttpObject() {
  try {return new XMLHttpRequest();}
  catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
  catch (error) {}

  throw new Error("Could not create HTTP request object.");
}

var request = makeHttpObject();
request.open("GET", "api/dev/blah?id=4F", true);
request.setRequestHeader("Accept", "application/xml");
request.setRequestHeader("Content-Type", "application/xml");
request.send(null);
request.onreadystatechange = function() {
    if (request.readyState==4 && request.status==200) {
        console.debug(request.responseText);
    }
};