简体   繁体   English

JavaScript从rest API获取JSON而无需重新呈现页面

[英]JavaScript get JSON from rest API without re-rendering the page

Problem 问题

I'm trying to query a rest API in javascript and use jQuery to parse and insert the results into my webpage. 我正在尝试在javascript中查询rest API并使用jQuery解析并将结果插入到我的网页中。 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. 在进行查询时,我相信它会提交搜索表单并重新呈现页面,从而删除我刚查询和插入的所有元素。

Is there away to get a JSON object from a rest api and not re-render the webpage? 是否有从休息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 我试过的

I can't return my json object 我无法返回我的json对象

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示例:

http://woof.magnify.net/api/content/find?vq=karma&per_page=5&page=1&sort=popularity&key=84LTHNZQ1364W14D&format=json http://woof.magnify.net/api/content/find?vq=karma&per_page=5&page=1&sort=popularity&key=84LTHNZQ1364W14D&format=json

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM