2013-08-04 135 views
-1

我需要訪問給我JSON對象並使用基本身份驗證的Web服務URL。我如何在JavaScript中執行相同的操作。我正在使用下面的代碼,但瀏覽器上沒有任何反應。請求Web服務以獲取JSON

<html> 
<head> 
<title>Hello World</title> 
<script> 

function send_with_ajax() 

    var httpRequest = new XMLHttpRequest(); 
    httpRequest.open("GET", 'url of service', true); 
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
    httpRequest.send(); 

    httpRequest.onload= function() { 
     if (httpRequest.readyState == 4) 
     { 
      var _tempRecommendations = httpRequest.responseXML; 
      window.alert(httpRequest.response); 
      window.alert(httpRequest.responseText); 
      window.alert(_tempRecommendations); 
     } 
    }; 
}; 

</script> 
</head> 
<body onload="send_with_ajax()"></body> 
</html> 
+0

設置用戶名和密碼。 – Musa

回答

1

檢查jQuery爲此操作。這將導致類似

$.get("http://yourRestprovider.com/yourResource",function(data){ 
    //handle your data 
    },"json"); 

請註明您有基本身份驗證的意思,因爲我沒有看到你的代碼片段對服務器進行身份驗證的方法!

0

(你不需要JQuery的這一點。)

首先確保內部功能運行在所有的,所以儘量的功能設定爲onreadystatechange,而不是onload

至於身份驗證:如果您的域名(代替'服務的url'的東西')與腳本所在的頁面具有相同的來源,並且您已經在進行某種身份驗證,它存儲了登錄會話Cookie ,你不需要做其他事情。

+0

嗨,如果我使用onreadystatechange我收到警報:響應和responseText(沒有任何警報)和_tempRecommendations爲空我怎麼能解決這個問題。 – zdhim

+0

對不起,我不清楚,觀察到的行爲是什麼? _tempRecommendations爲空,我明白了。你有沒有看到任何警報?空警報?但更重要的是,域名是否匹配?你在本地計算機上測試html文件嗎? – user2573802

-1

嗨,我使用下面的代碼:之後,它只顯示加載瀏覽器。

<html><head> 
<title>Hello World</title> 
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> 
<script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"> 
</script> 
<script type="text/javascript"> 

function send_with_ajax() 
{ 

     $.ajax 
     ({ 
      type: "GET", 
      url: "https://url with params", 
      dataType: 'json', 
      async: false, 
      username: 'abc', 
      password: 'def', 
      data: '{ "comment" }', 
      success: function(){ 
      alert('Success!'); 
      } 
     }); 
} 

</script> 
</head> 
<body onload="send_with_ajax()"></body> 
</html> 
+0

代碼已更新,但仍無法獲取json。 – zdhim