我遇到了问题。我正在尝试自己做 ajax,但我在保存 ajax 调用的结果时遇到问题。我希望它像 jQuery 一样或类似地做。 所以,我有一个名为 ajax 的函数,带有 I 参数,这个参数是一个具有如下属性的对象:method、url、async、data 和 success ... 当我调用 ajax 函数时,除了成功之外我没有任何问题。我想要它就像 jQuery(不要问我为什么我不想使用 jQ)。所以我想要这个
ajax({
method: "POST",
url: "ajax.php",
async: false,
data: "name=something",
success: function(result) {
console.log(result);
}
});
我在将结果保存到 ajax 函数定义中的参数时遇到了问题,这里只使用它。
这是ajax.php
<?php
$name = "The input is: " . $_POST['name'];
return $name;
?>
这是一个ajax函数的定义:
var ajax = function (arg) {
if (typeof arg.method !== "undefined" && typeof arg.url !== "undefined" && typeof arg.async !== "undefined"
&& typeof arg.success !== "undefined" && typeof arg.data !== "undefined") {
var xmlhttp, i = 0,
versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
for ( ; i < versions.length; i++) {
try {
xmlhttp = new ActiveXObject(versions[i]); break;
} catch (e) { }
}
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
/* ////////////////////////////////////////////
HERE I HAVE PROBLEM
/////////////////////////////////////////////*/
// this is obviously wrong (I know it is)
arg.success = function (something) {
something = xmlhttp.responseText;
}
} else if (xmlhttp.status == 400) {
console.log("There was an error 400");
} else {
console.log("UNSUCCESSFUL");
}
}
}
xmlhttp.open(arg.method, arg.url, arg.async);
xmlhttp.send(arg.data);
console.log("Method: " + arg.method + "\nURL: " + arg.url + "\nAsync: " + arg.async + "\nData: " + arg.data + "\n");
}
};
如何将 xmlhttp.responseText
保存到 arg.success
函数参数,以便我可以在 ajax 函数调用中使用该参数?我应该使用回调吗?
编辑:谢谢,它有效,但它只打印“输入是:”。我该如何解决?
最佳答案
您想调用该方法,而不是设置它。
arg.success(xmlhttp.responseText);
关于JavaScript Ajax 保存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32398752/