I have a string which is got from ajax result:
["name1", "name2", "name3", "name4", "name5"]
The string pattern is exactly as above, including ", and the total element is not fixed
I tried below code but doesn't work:
var strArr="";
$.ajax({url:"myurl",success:function(result){
strArr=result;
}});
var arr = new Array(strArr);
Update: This is my latest code
var strArr="";
$.ajax({url:"myurl",success:function(result){
strArr=result;
alert(strArr); //["name1", "name2", "name3", "name4", "name5"]
}});
var arr= JSON.parse(strArr);
To convert that string to an actual Array, just do JSON.parse, like this
var data = '["name1", "name2", "name3", "name4", "name5"]';
console.log(JSON.parse(data));
# [ 'name1', 'name2', 'name3', 'name4', 'name5' ]
You can confirm the type of object returned, like this
console.log(Object.prototype.toString.call(JSON.parse(data)));
# [object Array]
Your actual code, should look something like this
$.ajax({
url: "myurl",
success: function(result) {
alert(JSON.parse(result));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With