进行简单的 JS XmlHttpRequest 调用的问题 [英] Problem with making a simple JS XmlHttpRequest call

查看:46
本文介绍了进行简单的 JS XmlHttpRequest 调用的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我让问题变得比它应该的更复杂.我的问题是:如何从 JS 对服务器进行 API 调用.

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.

我必须创建一个非常简单的客户端,它向我们的服务器发出 GET 和 POST 调用并解析返回的 XML.我正在用 JavaScript 写这个,问题是我不知道如何用 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)!

作为第 n 个初始测试,我试图 ping 到 Twitter API,这是当用户输入 URL 时调用的函数 http://api.twitter.com/1/users/lookup.xml 并点击提交按钮:

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

当我在 FF 上运行这个时,我得到一个

When I run this on FF, I get a

访问受限 URI 被拒绝"代码:1012

Access to restricted URI denied" code: "1012

Firebug 上的错误.我用谷歌搜索的东西表明这是一个特定于 FF 的问题,所以我切换到 Chrome.在那里,第二个警报出现,但显示 0 作为 HTTP 状态代码,我觉得这很奇怪.

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.

谁能发现问题出在哪里?人们说这些东西与 JQuery 一起使用更容易,但是现在在 JS 语法之上学习那个有点太多了.

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.

推荐答案

出于安全原因,您不能使用 AJAX 请求来自不同域的文件.

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

由于您的 Javascript 未在 http://api.twitter.com 上运行,因此它无法从 http://api.twitter.com 请求文件.

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.

这篇关于进行简单的 JS XmlHttpRequest 调用的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆