显示从Ajax请求获取数据 [英] Getting Data from Ajax request displayed
问题描述
我已经阅读了这篇文章如何做我从异步调用返回响应吗?但是我无法提出解决方案. 我正在执行ajax请求
I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution. I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
控制台显示的一切正常,但是当我说
And Console displays everything fine but when I say
var chinese = getdata();
获取数据.我不断得到:
to get the data. I keep getting:
未捕获的TypeError:无法读取此行的未定义错误的属性"length"
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
有人可以在这里帮助我吗?
Can anybody help me here?
推荐答案
问题是您使用的是异步方法,希望获得同步结果.
The problem is that you are using an asynchronous method expecting a synchronous result.
因此,您应该在异步调用的结果中使用以下代码:
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
我希望它会有所帮助:)
I hope it helps :)
这篇关于显示从Ajax请求获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!