简体   繁体   中英

javascript code is not working in browser?

Here is my code it will send get request and renders some content of the response in 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>

this code is working perfectly when i run in eclipse browser. but its failing in Browser. I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.

Im new to javascript http requests. Please suggest

I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..

     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  }

In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser). Perhaps something like this

<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>

I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia] . That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.

And indeed if I try to run your code [jsFiddle] , I get the following error:

XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

There are multiple ways to work around the same-origin policy [SO] . In your case it seems that the service supports JSONP [SO] .

With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.

The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:

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

by adding the argument callback=foo to the URL, the server returns

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

(follow this URL to see an example for your service)

This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.

Here is a complete example:

// 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);
}

DEMO

If you google for JSONP, you will find more information [Wikipedia] and tutorials.

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();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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