解決ajax跨域訪問獲取資料返回json的方法
前段時間需要做一個iOSAPP ,但是資料需要從伺服器上獲取,就想到了介面的辦法,html頁面獲取上傳到伺服器上的資料,發現在使用ajax提交返回json時候,提示No 'Access-Control-Allow-Origin' header is present on the requested resource.
意思就是我通過不同域名 不同埠號 獲取資料,折騰了一天終於弄好。真是喜大普beng,頓時感覺面朝大海春暖花開的感覺,本屌訪問的後端程式碼是struts框架,通俗說就是一個連線到一個action,現提供解決方案,首先在自己要訪問的這個action方法中加入:
ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");
附上我的原始碼:
/**
* 查詢產品資訊介面
*
* @return
*/
public String findProductByIdJson() {
try {
// ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");
jsonProduct = productService.findbyProductId(product
.getProductId());
return "backJson";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
發現成功得到json資料
前端程式碼:
$.ajax({
url: "http://localhost:8080/gzxx1.4/product_findProductByIdJson.action?product.productId=22",
type: 'post',
dataType: 'JSON',//here
success: function (data) {
alert(data.productPreview);
}
});
最後想到所有介面方法都要加入這樣一句程式碼。靈機一動的我想到了攔截器,當然過濾器也行,攔截所有要跨域響應的方法。。。。。