Javascript XMLHttpRequest (Ajax) 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8866761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest (Ajax) Error
提问by Muricula
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:
我XMLHttpRequest
在 JavaScript 中使用。但是,它给了我一个错误,我不知道我的问题是什么。
我必须解析一个 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>
My XML file is inside the same directory.
我的 XML 文件位于同一目录中。
<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.
仅供参考,我通常使用 C# 或 Java 编程,并且我在 Google Chrome 上运行我的网站。
回答by Nadir Muzaffar
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:
首先阅读如何使用,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);
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.
其次,由于您收到 101 错误,您可能使用了错误的 URL。因此,请确保您发出请求的 URL 是正确的。另外,请确保您的服务器能够为您的quiz.xml
文件提供服务。
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:
您可能需要通过简化/缩小问题所在来进行调试。所以我会先做一个简单的同步请求,这样你就不必担心回调函数了。所以这是来自 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);
Also, if you're just starting out with Javascript, you could refer to MDNfor Javascript API documentation/examples/tutorials.
此外,如果您刚开始使用 Javascript,您可以参考MDN以获取 Javascript API 文档/示例/教程。
回答by supertopi
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
- XMLHTTPRequest 对象在您尝试使用它时尚未完成加载数据
Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
解决方案:为对象“onreadystatechange”-事件分配一个回调函数并处理该函数中的数据
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
一旦状态达到 DONE (4),响应内容就可以被读取了。
Problem 2
问题二
- the XMLHTTPRequest object does not exist in all browsers (by that name)
- XMLHTTPRequest 对象并非在所有浏览器中都存在(以该名称命名)
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
解决方案:使用 try-catch 为正确的浏览器创建正确的对象(IE 中的 ActiveXObject)或使用框架,例如jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
注意:如果你决定使用 jQuery ajax 方法,你可以使用 jqXHR.done() 分配回调函数
回答by CBusBus
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:
通过包含您所说的括号onload
应该等于onPageLoad()
. 例如:
/*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:
如果您将 的值打印window.onload
到控制台,它将是:
science
科学
The solution is remove the brackets:
解决办法是去掉括号:
window.onload = onPageLoad;
So, you're using onPageLoad
as a reference to the so-named function.
因此,您使用onPageLoad
作为对所谓函数的引用。
Finally, in order to get the response value you'll need a readystatechange
listener for your XMLHttpRequest
object, since it's asynchronous:
最后,为了获得响应值readystatechange
,您的XMLHttpRequest
对象需要一个侦听器,因为它是异步的:
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
}
}