【发布时间】:2020-03-07 12:59:28
【问题描述】:
我需要的是通过 javascript 重建prototype.js Ajax 请求。 (没有 jQuery / 没有获取)。需要 IE 支持(出于某些原因...)
new Ajax.Request(
urlVar,
{
method: 'post',
parameters: {elid: document.getElementById('element').selectedIndex},
onCreate: function(){
//do somethings
},
onComplete: fucnction (event){
currentValues = eval('(' + event.responseText + ')');
console.log(currentValues); // will give me an array with 3 objects
}
});
我试过的是:
var xhr = new XMLHttpRequest();
xhr.open("POST", urlVar, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function (event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
currentValues = eval('(' + event.responseText + ')');
console.log(currentValues); // i see an error that "currentValues" is undefined
//i can get 1 object if i will do eval('(' + THIS.responseText + ')');
// but it still bugs me a lot..
//other actions here
}
else if (xhr.status == 400) {
console.log('ERROR')
}
else {
console.log('something else other than 200 was returned');
}
}
}
xhr.send(document.getElementById('element').selectedIndex);
也许有人知道在这种情况下哪种构造会起作用。 有什么方法可以通过 js 进行 onCreate / onComplete 吗?
【问题讨论】:
-
永远不要
eval那个响应文本。使用JSON.parse。为那些没有它的老旧浏览器使用 polyfill。 -
你看
Ajax.Request的源码了吗?没那么复杂。 -
您得到的具体错误是什么?
-
我做错了什么,因为在 1 个示例(原型)-> 控制台日志中会显示一个包含 3 个对象的数组。但在 javascript 版本的情况下 -> 只有 1
-
您可能发送的参数有误。查看开发人员工具中的网络面板,了解请求的不同之处。我的猜测是您正在寻找
xhr.send("elid="+encodeURIComponent(…selectedIndex))。
标签: javascript ajax prototypejs