如何从 javascript 调用 REST API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14433212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:44:38  来源:igfitidea点击:

how to call REST API from javascript

javascriptjqueryhtml

提问by Rishi

I have a url which gives json data...

我有一个提供 json 数据的网址...

I want to hit that URL from javascript but I am getting this error :

我想从 javascript 访问该 URL,但出现此错误:

character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature

未声明纯文本文档的字符编码。如果文档包含来自 US-ASCII 范围之外的字符,则文档将在某些浏览器配置中呈现为乱码。文件的字符编码需要在传输协议中声明或者文件需要使用字节序标记作为编码签名

Code :

代码 :

function a(){
$.getJSON(url,function(data) { alert(data);});
}

full code :

完整代码:

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>
<script language="JavaScript" type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>

function a(){
$.getJSON(url,function(data) { alert(data);});
}
</script>
</head>
<body>
<input type="text"/>
<input type="submit" value="search" onclick="a()"/>
</body>
</html>

采纳答案by Wolf

Your code seems correct.

你的代码似乎是正确的。

Are you making a fully qualified URL call?

你在做fully qualified URL call吗?

If you are making a fully qualified URL call, make sure of the following.

如果您要进行完全限定的 URL 调用,请确保以下内容。

  1. You are calling the same domain(same server). You can not make a simple JSON call to another domain.
  2. If you want to use a cross domain call, you'll have to use JSONp
  1. 您正在调用同一个域(同一个服务器)。您不能对另一个域进行简单的 JSON 调用。
  2. 如果要使用跨域调用,则必须使用 JSONp

Update:This is not working since it is a cross domain call.

更新:这不起作用,因为它是跨域调用。

Work around for this

解决这个问题

JavaScript

JavaScript

Create a function

创建函数

function getMyData(data) {
    alert(data);
    //Do the magic with your data
}

Server side

服务器端

On server end wrap your data inside function syntax

在服务器端将您的数据包装在函数语法中

getMyData("Enter your data here");

JavaScript

JavaScript

Then create a script tag and add a link to your cross-domain page

然后创建一个脚本标签并添加一个链接到您的跨域页面

 <script type="text/javascript"
         src="cross ref url">
 </script>

For reference: wikipedia

供参考:维基百科

EDIT: Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

编辑:另一个选项是在您的域上创建代理。即在您的域中创建一个页面,该页面在内部调用跨域页面并将相同的数据返回到您的 Ajax 调用。