Problem with making a simple JS XmlHttpRequest call

最后都变了- 提交于 2020-01-03 05:20:09

问题


Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.

I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!

As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:

function doRequest() {
    var req_url, req_type, body;
    req_url = document.getElementById('server_url').value;
    req_type = document.getElementById('request_type').value;   
    alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
    req = new XMLHttpRequest();
    req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
    req.onreadystatechange=function() {
            if (req.readyState == 4) {
                    alert(req.status);
            }
    }
    req.send(null);
}

When I run this on FF, I get a

Access to restricted URI denied" code: "1012

error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.

Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.


回答1:


For security reasons, you cannot use AJAX to request a file from a different domain.

Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.

Instead, you can write server-side code on your domain to send you the file.



来源:https://stackoverflow.com/questions/2671147/problem-with-making-a-simple-js-xmlhttprequest-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!