AJAX - 返回响应文本
我在互联网上看到了无数关于 AJAX 请求中返回未定义的类似代码的线程:
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
我知道我应该“用”responseText“做一些事情”,比如将其写入 HTML 。问题是:我没有那种奢侈。这段代码旨在用于运行快速 AJAX 请求的通用方法中,这样发出 AJAX 请求的所有代码都不必一遍又一遍地写出(~40×),并且有可能出现轻微的错误。这里或那里的问题会破坏应用程序。
我的方法必须显式返回responseText
“否则”。 不写入 HTML。我该怎么做?另外,我希望缺少 JQuery 插件。
我正在寻找什么:
function doAjax(param) {
// set up XmlHttpRequest
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
// send data
}
...
function doSpecificAjax() {
var param = array();
var result = doAjax(param);
// manipulate result
}
I've seen the myriad threads sprawled across the Internet about the following similar code in an AJAX request returning undefined:
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
I know that I'm supposed to "do something with" responseText
like writing it to the HTML. The problem: I don't have that luxury. This bit of code is intended to be inside of a generic method for running fast AJAX requests that way all the code for making an AJAX request doesn't have to written out over and over again (~40×) with the chance of a minor problem here or there that breaks the application.
My method HAS to explicitly return responseText
"or else." No writing to HTML. How would I do this? Also, I'd appreciate a lack of plugs for JQuery.
What I'm looking for:
function doAjax(param) {
// set up XmlHttpRequest
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4) {
if(AJAX.status == 200) {
var response = AJAX.responseText;
return response;
}
else {
window.alert('Error: ' + AJAX.status);
return false;
}
}
};
// send data
}
...
function doSpecificAjax() {
var param = array();
var result = doAjax(param);
// manipulate result
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
做了一些研究,我发现了这篇 SOF 帖子:
Ajax responseText 返回未定义
根据该帖子,您可能会想要像这样实现你的ajax方法:
然后,你可以像这样调用该方法...
这应该准确地返回responseText。如果这不能给您返回正确的结果,请告诉我。
Doing a little research I came across this SOF post:
Ajax responseText comes back as undefined
Based on that post, it looks like you may want to implement your ajax method like this:
Then, you can call that method like this...
This should return the responseText accurately. Let me know if this doesn't give you back the correct results.