开发者

No reply received using XmlHttpRequest

开发者 https://www.devze.com 2023-02-13 11:47 出处:网络
I am trying to write a small script, which can send a request and download a json response. var xmlhttp = false;

I am trying to write a small script, which can send a request and download a json response.

var xmlhttp = false;

    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microso开发者_高级运维ft.XMLHTTP");
      }

      xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4)
        {
         // I tried checking for status but that is always coming 0
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText+"a";
        }
      }*/
      var url = 'http://exampleurl.com/api?input=a@b.com';
    xmlhttp.open('GET',url,true);
    xmlhttp.send(null);

Now if I replace the URL with a text file, it works fine. However my server is replying in JSON encoding. Also if I visit the URL in my browser, it shows me the desired output.

However when I query it using XmlHttpRequest it always gives me a status of 0, and has a null response (nothing to decode).


Did you try URL encoding your query parameters? Looks like you might be sending across special characters.

As kjy112 mentioned, there are limitations to making client-side requests to other domains, even sub-domains - same origin policy..

Update: Inder, see http://en.wikipedia.org/wiki/Same_origin_policy, this is a security mechanism that prevents what you are trying to do.

Here is how you can solve it: Have your server make the call on behalf of your client. What I mean by that, is take the call you were going to make from the browser(via AJAX), and make it a web service on the server. Then have your AJAX call go to your server, which will then make the call and return the response. So, you're using your server as an intermediary.

Or

If it's a public API, they are probably configured for JSONP (http://ajaxian.com/archives/jsonp-json-with-padding)


I usually validate xmlhttp.status after validating readyState (200 is what you want)

Have you tried checking xmlhttp.statusText to see if it holds anything interesting?

0

精彩评论

暂无评论...
验证码 换一张
取 消