Try   HackMD

Angular10 用 httpClient 獲取 jsonp 資料方式

tags: Angular jsonp

JSONP(JSON with Padding)是解決跨網域限制的方法之一

使用angular http jsonp 第二個參數可以帶入callback 名稱,他會帶上一個value,那個 value 就是伺服器要回傳script callback 的function名稱

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

前端:(此範例是使用 NG-ZORRO select )

this.http
      .jsonp<{ result: Array<{ recno: number; content: string }> }>(
        `http://aaa.bbb.ccc/api/jsonp`,
        'callback'
      )
      .subscribe((data) => {
        const listOfOption: Array<{ value: number; label: string }> = [];
        data.result.forEach((item) => {
          listOfOption.push({
            value: item.recno,
            label: item.content,
          });
        });
        this.listOfOption = listOfOption;
      });

後端(java):

String callback = req.getParameter("callback");

JSONArray res_arr = new JSONArray();

JSONObject result = new JSONObject();
result.put("result", res_arr);

resp.getWriter().append(callback + "(" + result + ")").close();