[英]jQuery ajax call to REST service
我正在嘗試從jquery到休息服務進行ajax調用。 使用的其他服務正是來自mkyong博客的教程,這個: http ://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/
該服務有效,但是當我嘗試從jQuery調用時,在Firebug中有一個200狀態代碼,但在響應部分中沒有任何內容。
這是帶有ajax調用的html頁面:
<html>
<head>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<button id="ajax">ajax call</button>
<button id="json">json</button>
<script type="text/javascript">
$('#json').click(function(){
alert('json');
$.getJSON("http://localhost:8080/restws/json/product/get",
function(data) {
alert(data);
});
});
$('#ajax').click(function(){
alert('ajax');
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
});
</script>
</body>
</html>
我無法弄明白我哪里出錯了,你能不能告訴我我做錯了什么?
謝謝!
您從與請求的主機不同的主機運行HTML。 因此,您將受到相同原始策略的阻止。
解決這個問題的一種方法是使用JSONP 。 這允許跨站點請求。
在JSON中,您將被返回:
{a: 5, b: 6}
在JSONP中,JSON包含在函數調用中,因此它變為腳本,而不是對象。
callback({a: 5, b: 6})
您需要編輯REST服務以接受名為callback
的參數,然后使用該參數的值作為函數名稱。 您還應該將content-type
更改為application/javascript
。
例如: http://localhost:8080/restws/json/product/get?callback=process
應輸出:
process({a: 5, b: 6})
在JavaScript中,您需要告訴jQuery使用JSONP。 要做到這一點,你需要追加?callback=?
到URL。
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
如果你使用$.ajax
,它會自動追加?callback=?
如果你告訴它使用jsonp
。
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
從8080的使用我假設你使用一個tomcat servlet容器來為你的api服務。 如果是這種情況,您還可以考慮讓您的Web服務器代理對servlet容器的請求。
使用apache,您通常會使用mod_jk(盡管還有其他選擇)通過端口80后面的Web服務器而不是8080來處理api,這將解決跨域問題。
這是常見做法,在Web服務器中具有“靜態”內容,在容器中具有動態內容,但兩者都在同一域后面提供。
其余api的url為http://localhost/restws/json/product/get
這里有關於如何使用mod_jk將apache連接到tomcat的描述: http : //tomcat.apache.org/connectors-doc/webserver_howto/apache.html
我認為沒有必要指明
'http://localhost:8080`"
在URI部分..因為。 如果您指定它,則必須為每個環境手動更改它。
只要
"/restws/json/product/get" also works
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.