[英]how to return result from AJAX javascript using POST [not using jquery]?
function AJAX(url,data)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
var a = AJAX('log.php','username=Leonard&password=asjdklaslkjdalskjdlaksjda');
When the function return it gives me "undefined". 当函数返回时,它给我“未定义”。
Your function is asynchronous - it doesn't wait for the AJAX call to complete before returning so there's no results to return. 您的函数是异步的-在返回之前,它不等待AJAX调用完成,因此没有返回结果。
Try this: 尝试这个:
function AJAX(url, data, callback, ctx)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4)
{
callback.call(ctx, xmlhttp.responseText);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
Note how you now have to supply a "callback function" that'll be invoked when the AJAX completes: 请注意,您现在必须提供一个“回调函数”,当AJAX完成时将被调用:
AJAX('log.php','username=Leonard&password=asjdklaslkjdalskjdlaksjda',
function(result) {
// do stuff with result
}
);
EDIT the ctx
parameter I added is optional - it's so that you can set what this
will be when the callback is invoked. 编辑 ctx
我添加的参数是可选的-它让你可以设置什么this
被调用的回调时,会。 This (no pun intended) will be useful if the callback is a method of an object rather than a standalone function. 如果回调是对象的方法而不是独立的函数,则此方法(无双关语)将很有用。
When you returns xmlhttp.responseText
, you're returning to the onreadystatechange
property. 当returns xmlhttp.responseText
,您将返回到onreadystatechange
属性。 Not very useful, is it? 不是很有用,是吗?
Instead, use the asynchronous behavior to do the following: 而是,使用异步行为执行以下操作:
function AJAX( url, data, callback ) {
// Your stuff
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState === 4 ) {
callback( xmlhttp.responseText )
}
}
// Your other stuff
}
Then, you can use it like: 然后,您可以像这样使用它:
AJAX( url, data, function( responseText ) {
// use responseText there
} )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.