【问题标题】:Showing the output of a JSON request显示 JSON 请求的输出
【发布时间】:2012-08-27 22:32:45
【问题描述】:

JSON 网址:http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=

这里的“str”可以是任意 2-3 个字符,例如 str = 'nas' 然后是 JSON URL:http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=nas&namespace=0&suggest=

我想获取所有结果并将这些结果放在一个表格中

我尝试过 AJAX、JSON、JQUERY 任何人都可以向我发送执行此操作的工作代码。

我的虚拟代码为:-

<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
function FillSearchBox(str)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {

        if (xmlhttp.readyState==4 && xmlhttp.status=200)
        {
            //Pointer never Comes in this Section (If I Debuug I got xmlhttp.status=0 every time) 
            var JSONObject = JSON.parse(xmlhttp.responseText);
        }
    }
    var strr= "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=";
    xmlhttp.open("GET",strr,true);
    xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" name="wikisearch" id=""   onkeyup="FillSearchBox(this.value)" />
</form>
<!-- add Table or Div Here -->
</body>
</html>

【问题讨论】:

  • 不能进行跨域 JSON 请求。 mediawiki 提供 jsonp 吗?
  • 是的,mediawiki 确实执行 jsonp - 您使用 callback 查询参数和您要调用的函数的名称。

标签: javascript ajax json


【解决方案1】:

需要使用 JSONP 进行跨域请求:

function gotData(d) { alert(d); }

var s = document.createElement('script');
s.src = "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&callback=gotData";
s.appendTo(document.body);

请注意,使用 jQuery 会更容易。

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2013-09-01
    • 2013-04-15
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多