Ajax以相同的逻辑返回不同的输出 [英] Ajax Returning different output in same logic
问题描述
我正在尝试下面的代码通过AJAX返回一个数组并尝试提醒返回值,但是在使用相同逻辑获取正确值时它显示未定义。
I'm trying below code to return an array by AJAX and try to alert the return value but its showing me undefined while getting correct value with the same logic.
这是我的HTML& JS代码:
Here is my both HTML & JS code:
HTML
<body>
<div>
<input type="button" id="getMI" />
</div>
</body>
JS代码(未定义)
var getId = function () {
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
contentType: "application/json",
success: function (res) {
objLen = res.length;
var arrElems = [];
for (i = 0; i < objLen; i++) {
arrElems[i] = res[i].ids;
}
return arrElems;
},
error: function (e) {
return e;
}
})
}
JS代码(获取正确的值)
var getId = function(){
var nums = [];
for(i=0;i<5;i++)
{
nums[i] = i+1;
}
return nums;
}
警报值
$('#getMI').click(function(){
var ids = getId();
alert(ids)
})
当我直接警告输出时(block_faces) )它给我正确的
值,但是当我试图返回它显示未定义时。
When I directly alert the output (block_faces) its giving me correct value but when I try to return that its showing undefined.
任何人都可以帮助我知道哪里出错了?
Can anyone help me to know where I'm going wrong?
推荐答案
伙计们我想分享一些关于解决问题的方法。为了成功拨打电话,我使用了 async:false 之后的建议,但后来我遇到了一些问题。我在Safar浏览器上无法获得成功响应这样的问题。在这里发布问题后,我发现使用 async:false 是完全错误的做法。
Guys I would like to share something I came to know about solution of my issue. To make call successfully I've used async:false following one of the suggestion but I got some issues later on. Issue like I was not able to get success response on Safar browser. After posting a question here I came to know that using async:false is totally wrong approach.
这里我粘贴评论链接和讨论。
Here I'm pasting the link of comments and discussion on that.
希望它能帮到你们。谢谢。
Hope it'll help you guys. Thanks.
这篇关于Ajax以相同的逻辑返回不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!