JavaScript 从 rest API 获取 JSON 而无需重新渲染页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18324058/
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
JavaScript get JSON from rest API without re-rendering the page
提问by agconti
Problem
问题
I'm trying to query a rest API in javascript and use jQuery to parse and insert the results into my webpage. When the query is made I believe it submits the search form and re-renders the page thus removing all of the elements I just queried and inserted.
我正在尝试在 javascript 中查询 rest API 并使用 jQuery 来解析结果并将其插入到我的网页中。当进行查询时,我相信它会提交搜索表单并重新呈现页面,从而删除我刚刚查询和插入的所有元素。
Is there away to get a JSON object from a rest api and not re-render the webpage?
是否可以从rest api获取JSON对象而不重新呈现网页?
Here's what I'm using to make my requests:
这是我用来提出请求的内容:
function get_data(){
var url = "www.rest_api/search_term&apikey=My_Key"
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
The search term comes from a simple input form, and is submitted when the submit button is clicked. My goal is to keep this webpage to a single page and avoid a results page.
搜索词来自一个简单的输入表单,并在单击提交按钮时提交。我的目标是将此网页保留在单个页面上并避免出现结果页面。
What I've tried
我试过的
Get JSON data from external URL and display it in a div as plain text
从外部 URL 获取 JSON 数据并将其显示在 div 中作为纯文本
http://api.jquery.com/jQuery.getJSON/
http://api.jquery.com/jQuery.getJSON/
Request URL example:
请求 URL 示例:
回答by Neil S
Remember when calling jsonp apis, you have to add an additional parameter to the url : callback=?
请记住,在调用 jsonp apis 时,您必须在 url 中添加一个额外的参数: callback=?
here's a simple fiddle as an example: http://jsfiddle.net/8DXxN/
这里有一个简单的小提琴作为例子:http: //jsfiddle.net/8DXxN/