javascript代码在浏览器中不起作用

javascript code is not working in browser?

本文关键字:不起作用 浏览器 代码 javascript      更新时间:2024-03-06

这是我的代码,它将发送get请求并以html格式呈现响应的一些内容。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
    <script type="text/javascript">
        function httpGet() {
            var xmlHttp = null;
            var x = document.getElementById("city").value;
            var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", url, false);
            xmlHttp.send();
            var obj1 = JSON.parse(xmlHttp.responseText.toString());
            document.getElementById("placeholder").innerHTML = obj1.message
                    + " " + obj1.list[0].name;
        }
    </script>
    <input type="text" id="city" />
    <input type="button" value="submit" onclick="httpGet()" />
    <div id="placeholder"></div>
</body>
</html>

当我在eclipse浏览器中运行时,这段代码运行得很好。但在浏览器中失败了。我已经检查了浏览器配置的脚本启用及其启用情况。并且浏览器配置也没有问题。

我是javascript http请求的新手。请建议

我在某处读到Eclipse浏览器不遵守同源策略[Wikipedia]。这就是为什么可以向外部URL发出Ajax请求,而这在"正常"浏览器中是不可能的。

事实上,如果我试图运行您的代码[jsFiddle],我会得到以下错误:

XMLHttpRequest无法加载http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json。请求的资源上不存在"Access Control Allow Origin"标头。因此,不允许原始'http://fiddle.jshell.net'访问。

有多种方法可以处理同源策略[SO]。在您的情况下,该服务似乎支持JSONP[SO]

使用JSONP,您不会对服务器进行Ajax调用,而是将URL与动态创建的脚本元素一起使用。脚本元素不受同源策略的限制,因此可以从其他服务器加载数据(代码)。

服务器将返回一个JavaScript文件,其中包含一个函数调用。函数的名称由您通过查询参数指定。因此,如果JSON响应通常是:

{"message":"accurate","cod":"200", ...}

通过在URL中添加参数callback=foo,服务器返回

foo({"message":"accurate","cod":"200", ...});

(按照此URL查看您的服务示例)

此响应可以作为JavaScript进行评估请注意您可以而不是将每个JSON响应转换为JSONP。服务器必须支持JSONP。

下面是一个完整的例子:

// this function must be global since the script is executed in global scope
function processResponse(obj1) {
    document.getElementById("placeholder").innerHTML = 
        obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
    var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
    // the following line is just to explictly show the `callback` parameter
    url += '&callback=processResponse';
    //                ^^^^^^^^^^^^^^^ name of our function
    var script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
}

演示

如果你在谷歌上搜索JSONP,你会发现更多信息[维基百科]和教程。

我认为没有创建您的xmlhttprequest实例。这是一段时间的浏览器依赖尝试这个。。

     var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 { your code  }

除了需要一个跨浏览器的xmlhttpquest(仅此一点,我会使用jQuery)之外,您还需要等待文档准备好,然后才能通过id访问城市…也就是说,在城市定义之后移动脚本块(我认为您可能需要一个表单,具体取决于浏览器)。也许像这个

<body>
  <form>
    <input type="text" id="city" />
    <input type="button" value="submit" onclick="httpGet()" />
  </form>
  <script type="text/javascript">
    function httpGet() {
        if (typeof (document.getElementById("city")) == 'undefined') {
          alert("Maybe console.log our alarm... but the sky appears to be falling.");
        }
        var xmlHttp = null;
        if (window.XMLHttpRequest)
        { // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
          if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            var obj1 = JSON.parse(xmlHttp.responseText.toString());
            document.getElementById("placeholder").innerHTML = obj1.message
                + " " + obj1.list[0].name;
          }
        }
        var x = document.getElementById("city").value;
        var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
        xmlHttp.open("GET", url, false);
        xmlHttp.send();
      }
  </script>
  <div id="placeholder"></div>
</body>
function httpGet() {
    var xmlHttp = null;
    var x = document.getElementById("city").value;
    var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", url, false);
    xmlHttp.onreadystatechange = function(){
         var obj1 = JSON.parse(xmlHttp.responseText.toString());
         document.getElementById("placeholder").innerHTML = obj1.message
                    + " " + obj1.list[0].name;
    }
    xmlHttp.send();
 }