2012-07-09 75 views
1

尋找一些幫助,使用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'); 
} 
}); 

我已經試過類似的東西到這一點,但我無法看到提琴手發送的請求,暗示無響應或錯誤(不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'); 
} 
+2

你能解釋一下你需要什麼特別的幫助?你是否得到錯誤等? – dstarh 2012-07-09 21:26:12

回答

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); 
    } 
}; 
+0

Thx回覆。出於某種原因,對request.setRequestHeader的調用沒有返回。那裏有任何想法?請求在檢查if(請求)後是否有效... – JaJ 2012-07-09 22:09:45

+0

您需要在'open'之後和'send'之前設置標題。從Firebug控制檯測試,修復了我的答案。 – Wolfram 2012-07-09 22:16:21

+0

是的,剛剛發現你剛剛迭代(thx)...我注意到的一件事是,我的xml由於某種原因在onreadystatechange()函數中返回兩次。有關於此的任何想法? – JaJ 2012-07-09 22:27:25

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

問題是XHR不響應加載事件。它與onreadystatechange迴應:

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