如何在javascript中从远程读取json [重复]

时间:2022-11-27 22:34:19

This question already has an answer here:

这个问题在这里已有答案:

I have tried to read a json from remote server, then i got this error.

我试图从远程服务器读取一个json,然后我收到此错误。

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource"

“阻止跨源请求:同源策略禁止读取远程资源”

Then i read that i need to set the datatype to jsonp.

然后我读到我需要将数据类型设置为jsonp。

  dataType: 'jsonp',

The problem is the json that i am getting isn't in jsonp format, which is required by jsonp. If i don't use jsonp i get the above error message.

问题是我得到的json不是jsonp格式,这是jsonp所要求的。如果我不使用jsonp我得到上面的错误信息。

How can I resolve this?

我该如何解决这个问题?

1 个解决方案

#1


0  

You have to enable a CORS request on the server side as well.

您还必须在服务器端启用CORS请求。

Add this line to your code: response.addHeader("Access-Control-Allow-Origin", "*");

将此行添加到您的代码中:response.addHeader(“Access-Control-Allow-Origin”,“*”);

You can replace * with your site's url if you want to allow only for particular domain.

如果您只想允许特定域名,则可以将*替换为您网站的网址。

#1


0  

You have to enable a CORS request on the server side as well.

您还必须在服务器端启用CORS请求。

Add this line to your code: response.addHeader("Access-Control-Allow-Origin", "*");

将此行添加到您的代码中:response.addHeader(“Access-Control-Allow-Origin”,“*”);

You can replace * with your site's url if you want to allow only for particular domain.

如果您只想允许特定域名,则可以将*替换为您网站的网址。