从Ajax方法返回字符串结果 [英] Returning String Result from Ajax Method
问题描述
我有一个DoughnutChart图表,我想更改其部分颜色与数据库中保存的颜色hexa代码我使用此Ajax方法通过调用返回JSON结果的操作方法来获取颜色字符串,
I have a DoughnutChart chart and I would like to change the color of its parts regarding color hexa-codes saved in the database I used this Ajax method to get the color string by invoking an action method that returns JSON Result ,
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// return data;
},
error: function (data) {
// return "Failed";
},
async: true
});
但不是接收字符串我在控制台窗口中收到了对象{readyState:1}
but instead of receiving the string I received Object {readyState: 1} in the console window
但是,我可以找到存储在ResponseText元素中的颜色值。我需要你的帮助我如何获得颜色值字符串。
However, I can find the color value stored in ResponseText element.I need your help in how can I get the color value as string.
编辑:
为了让事情更清楚,我会在哪里喜欢调用ajax方法来接收颜色字符串然后我就可以推入图表颜色数组了。
To make things more clear that's where I would like to invoke the ajax method to receive the color string then I will be able to push in the chart color array .
getColorArray: function getColorArray(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
console.log(this.getcolors("Risk"));
//colors.push(this.getcolors(categories[i]));
}
return colors;
}
推荐答案
为什么你的代码是这样的?
Why your code is like this?
success: function (data, textStatus, jqXHR) {
// return data;
},
你用过吗?
success: function (data, textStatus, jqXHR) {
console.log(data);
}
好的,我明白了。当您使用ajax请求时,您将使用异步数据,为此,您需要在方法中返回一个promise。请尝试使用以下代码。
Ok, i got it. When you use an ajax request your will work with asynchronous data, to do this you need return a promise in your method. Please, try to use the code below.
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
使用此功能时使用此代码:
And for use your function use this code:
getcolors("name").done(function(result){
console.log(result);
});
或者你可以使用回调
getcolors: function getcolors(name, success, error) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
success(data);
},
error: function(data){
error(data);
}
});
}
...以及与回调一起使用:
... And for use with callbacks:
getcolors("name", function(data){
//success function
console.log(data);
}, function(){
//Error function
console.log(data);
})
尝试其中一个选项并告知结果。
Try one of this options and tell the result.
这篇关于从Ajax方法返回字符串结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!