ajax responsetext为空,javascript - Ajax responseText comes back as undefined - Stack Overflow

Update based on your edit

function getData(callback)

{

// you should move the creation of xmlhttp in here

// so you can make multiple getData calls if needed

// if you keep xmlhttp outside the function the different calls to getData will interfere

// with each other

xmlhttp.open("GET", URL ,false); // false should be true, to make it async

...

{

alert(xmlhttp.responseText);

cbfunc(xmlhttp.responseText); // your function gets passed as the

// parameter "callback" but you're

// using "cbfunc" here instead of "callback"

...

getData(function cbfoo(txt) // you can omit the function name here

...

Fixing those issues should make the code work.

Old answer

You're calling the XMLHttpRequest in Synchronous mode, that means that it will block the script until the request has finished, since you're assigning the onreadystatechange callback after the blocking call (that means after the request has already finished) your code never gets notified.

Since the synchronous mode blocks the script, it also blocks the Browser's UI, so it's not recommended to use this mode.

You should (for 99% of the cases) use the Asynchronous mode and use a callback to handle the data, since xmlhttp.open does not return the return value of the onreadystatechange callback, it simply returns undefined immediately when run in async mode.

Now a common pattern is to write a wrapper for the request and pass an anonymous function to this wrapper, which later will get called back when the request has finished.

function doRequest(url, callback) {

var xmlhttp = ....; // create a new request here

xmlhttp.open("GET", url, true); // for async

xmlhttp.onreadystatechange=function() {

if (xmlhttp.readyState==4) {

if (xmlhttp.status == 200) {

// pass the response to the callback function

callback(null, xmlhttp.responseText);

} else {

// pass the error to the callback function

callback(xmlhttp.statusText);

}

}

}

xmlhttp.send(null);

}

You can now do a request and supply a function that will get called as soon as the request finishes, inside of that function you then do whatever you want to do with the response.

doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function

if (err) {

alert('Error: ' + err);

} else {

alert('Response: ' + response);

}

});

This is the common programming model in the browser, always go with a asynchronous solution, if you block the script you block the whole Browser.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值