XMLHttpRequest (Ajax) 错误

发布于 2024-12-27 05:01:01 字数 1139 浏览 0 评论 0原文

我在 JavaScript 中使用 XMLHttpRequest 。但是,它给了我一个错误,我不知道我的问题是什么。
我必须解析 XML 文件并将其内容分配给网页 - 这是我的代码:

<script = "text/javascript">

    window.onload = onPageLoad();
    var questionNum = 0;

    function onPageLoad(questionNum) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","quiz.xml");
        try {
            xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown 
        } catch(err) {
            document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
        }
        xmlDoc = xmlhttp.responseXML;
        parser = new DOMParser(); // This code is untested as it does not run this far.
    }
</script>

我的 XML 文件位于同一目录中。

<question>
    <query>what is 2+2?</query>
    <option>4</option>
    <option>5</option>
    <option>3</option>
    <answer>4</answer>
</question>

仅供参考,我通常使用 C# 或 Java 进行编程,并在 Google Chrome 上运行我的网站。

I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is.
I have to parse an XML file and assign its contents to the webpage - here's my code:

<script = "text/javascript">

    window.onload = onPageLoad();
    var questionNum = 0;

    function onPageLoad(questionNum) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","quiz.xml");
        try {
            xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown 
        } catch(err) {
            document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
        }
        xmlDoc = xmlhttp.responseXML;
        parser = new DOMParser(); // This code is untested as it does not run this far.
    }
</script>

My XML file is inside the same directory.

<question>
    <query>what is 2+2?</query>
    <option>4</option>
    <option>5</option>
    <option>3</option>
    <answer>4</answer>
</question>

Just for reference, I typically program in C# or Java, and I'm running my website on Google Chrome.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼眸 2025-01-03 05:01:01

所以这里可能有一些问题。

首先阅读如何使用 XMLHttpRequest.open() 因为还有第三个可选参数用于指定是否发出异步请求,默认为 true。这意味着您正在发出异步请求,并且需要在执行 send() 之前指定回调函数。这是来自 MDN 的示例:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

其次,由于您收到 101 错误,您可能使用了错误的网址。因此,请确保您发出请求所使用的 URL 正确。另外,请确保您的服务器能够为您的 quiz.xml 文件提供服务。

您可能必须通过简化/缩小问题所在来进行调试。因此,我首先发出一个简单的同步请求,这样您就不必担心回调函数。这里是来自 MDN 的另一个用于发出同步请求的示例:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

另外,如果您刚刚开始使用 Javascript,您可以参考 MDN 用于 Javascript API 文档/示例/教程。

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

南城追梦 2025-01-03 05:01:01

我看到 2 个可能的问题:

问题 1

  • XMLHTTPRequest 对象在您尝试使用它时尚未完成加载数据

解决方案:
将回调函数分配给对象“onreadystatechange”事件,并

xmlhttp.onreadystatechange = callbackFunctionName;

状态发生后 处理该函数中的数据 已到达 DONE (4),响应内容已准备好读取。

问题 2

  • XMLHTTPRequest 对象并不存在于所有浏览器中(按该名称)

解决方案:
使用 try-catch 为正确的浏览器创建正确的对象(IE 中的 ActiveXObject)或使用框架,例如 jQuery ajax-method

注意:如果您决定使用 jQuery ajax-method,请使用 jqXHR.done() 分配回调函数

I see 2 possible problems:

Problem 1

  • the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it

Solution:
assign a callback function to the objects "onreadystatechange" -event and handle the data in that function

xmlhttp.onreadystatechange = callbackFunctionName;

Once the state has reached DONE (4), the response content is ready to be read.

Problem 2

  • the XMLHTTPRequest object does not exist in all browsers (by that name)

Solution:
Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method

Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()

以歌曲疗慰 2025-01-03 05:01:01

问题可能在于以下行:

window.onload = onPageLoad();

通过包含括号,您表示 onload 应等于 onPageLoad() 的返回值。例如:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

如果将 window.onload 的值打印到控制台,它将是:

科学

解决方案是删除括号:

window.onload = onPageLoad;

因此,您使用 onPageLoad 作为对所谓函数的引用。

最后,为了获取响应值,您需要为 XMLHttpRequest 对象提供一个 readystatechange 侦听器,因为它是异步的:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

在这里添加侦听器:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}

The problem is likely to lie with the line:

window.onload = onPageLoad();

By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

If you print out the value of window.onload to the console it will be:

science

The solution is remove the brackets:

window.onload = onPageLoad;

So, you're using onPageLoad as a reference to the so-named function.

Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

Here you add the listener:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文