栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Ajax responseText返回为未定义

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Ajax responseText返回为未定义

根据您的修改进行更新

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 ...

解决这些问题应可使代码正常工作。

旧答案

您正在以 同步 模式调用XMLHttpRequest ,这意味着它将 阻塞
脚本,直到请求完成为止,因为您是

onreadystatechange
在阻塞调用之后(即请求已经完成之后)分配回调,因此您的代码永远不会收到通知。

由于同步模式会阻止脚本,因此它也会阻止浏览器的UI,因此不建议使用此模式。

您(在99%的情况下)应使用 异步 模式并使用回调来处理数据,因为

xmlhttp.open

返回
onreadystatechange
回调的返回值,因此仅
undefined
在异步模式下运行时立即返回。

现在,一种常见的模式是为请求编写一个包装器,并将一个 匿名 函数传递给该包装器,稍后,该请求将在请求完成后被回调。

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);}

现在,您可以执行一个请求,并提供一个将在请求完成后立即被调用的函数,然后在该函数内部执行您想对响应执行的任何操作。

doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function    if (err) {        alert('Error: ' + err);    } else {        alert('Response: ' + response);    } });

这是浏览器中的通用编程模型,始终与异步解决方案一起使用,如果您阻止脚本,则将阻止整个浏览器。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415674.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号