【问题标题】:hi how can i fetch json from a url using javascript [duplicate]嗨,我如何使用 javascript 从 url 获取 json [重复]
【发布时间】:2017-05-24 17:37:23
【问题描述】:

我正在尝试构建一个具有关键功能的浏览器扩展,包括从 html 页面获取文本输入并将其与 URL 连接并从该连接 URL 获取 json。

我想知道如何使用 JavaScript 从 URL 获取 json 到变量。

这是抓取用户插入文本的 html 脚本。

<html>
<body>
<input type="text" id="search" name="Name" maxlength="10" class="searchField" autocomplete="off" title="" ><br>
  </p>
</form>
<p align="center">
<button type="button" id="srchbutton" style="background-color:Thistle;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:%"> Search</button>
</p>
<script language="javascript" type="text/javascript" src="thanq.js">
    var button= document.getElementById('srchbutton');
    button.onclick= linkprocess();
    console.log("hi there");
</script>
</body>
</html>

这是我试图从 URL 访问 json 的 JavaScript。

var oldlink='URL';
var newlink;
function linkprocess(links){
    var text= document.getElementById('search');
   newlink=oldlink+text;
   GetJson(newlink);
   console.log(newlink);
}

【问题讨论】:

  • 你需要支持哪些浏览器?
  • 试试这个$.getJSON('newlink', function(data) { console.log(data) })
  • 使用 jQuery 的 $.getJSON() 或学习原始的 XMLHttpRequests,如果您正在学习,我建议您这样做。

标签: javascript html json


【解决方案1】:

您可以在纯 javascript 中使用 xmlhttp 请求来执行此操作。看看这篇w3学校的文章:JSON Http Request

为了简化编写的代码,您可以在熟悉该机制后使用 jQuery 的 $.get() 或 $.ajax() 方法。

【讨论】:

    【解决方案2】:

    或者您可以使用现代的fetch API,例如:

    const searchVal = document.getElementById('search').value;
    
    fetch('http://someprefix/' + searchVal)
      .then(response => response.json())
      .then(data => {
        console.log('Fetched:', data);
      })
      .catch(err => {
        console.error('Fetch error:', err);
      });
    

    【讨论】:

    • 只是不要指望它可以在许多浏览器上工作。
    • 是的,你可以加载一个 polyfill - github.com/github/fetch,但这看起来更像是一个实验而不是生产代码
    • @PHPglue - 它不能在 IE 和“新 IE”(即 Safari)中本机工作 - 否则支持非常普遍
    猜你喜欢
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多