ajax獲取後台json資訊時跨域

2021-08-13 20:00:25 字數 884 閱讀 6583

問題描述:

1. 使用ajax接收後台傳遞過來的轉化為string型別的json資料時進入error函式,

2. 且alert()方法列印出在error中獲取到的responsetext內容為空,

3. 使用chrome瀏覽器,在console頁面看到報錯:no 'access-control-allow-origin' header is present on the requested 

分析原因:http請求跨域被攔截

解決方法:

在後台response中追加設定:response.setheader("access-control-allow-origin", "*");

結果:可正常獲取資料

備註:access-control-allow-origin:* 表示允許任何網域名稱跨域訪問

如果需要指定某網域名稱才允許跨域訪問,只需把access-control-allow-origin:*改為access-control-allow-origin:允許的網域名稱

例如在這裡我的tomcat執行在ip=192.168.1.100的本地,所以可以設定:response.setheader("access-control-allow-origin", "");

如設定*,請注意跨域風險

例如:header('access-control-allow-origin:');

附上部分**:

後台:

jsonarray returnjson=jsonarray.fromobject(jsonmap);

try catch (ioexception e)

return null;  //使用了struts2,所以用return null阻止跳轉}

前端部分:

submit

Ajax小案例之獲取後台資訊顯示

知識點 資料傳輸 json jquery aj ax 原理 son 的資料使 用php file getc onte nts 方法在 後台獲取 到在前台 使用.ajax 原理 son的資料 使用php file get contents 方法在後台獲取到 在前台使用 ajax 原 理 so n的資料...

關於ajax獲取的後台資料轉換為JSON物件

在ajax請求獲取的資料時string型別,對於用js操作這些資料有很大的阻撓,如果轉換為json物件就很容易操作了。舉個例子 var data this.responsetext console.log data 其餘 不贅述了,這裡我用data接受了假資料的內容,我們看一下輸出內容 資料內容過多...

ajax請求後台互動json示例

ajax請求,首先需要伺服器 首先你需要node 其次,進入當前目錄 預設伺服器端口8080 http server 推薦封裝ajax,以及ajax轉碼過來或者轉碼回去後台 1 doctype html 2 html 34 head 5 meta charset utf 8 6 title docu...