I have a code like this :
var width = [];
$.ajax({
url : "http://xxx.xxx.xxx" ,
type : "Get",
dataType: "json",
async : true,
success : function(data){
for (var index in data)
{
var options = data[index].option;
var position = (++index);
width[index] = new Array();
for (var keys in options)
{
width[index][keys] = options[keys].votes;
}
}
}
});
in the chrome browser, it works fine, but in the safari, the error look likes:
TypeError: undefined is not an object (evaluating 'width[index][keys] = options[keys].votes')
But if I open debug mode in safari, there is no error, so what's the problem in this code?
I change my for loop code like this:
for (var index = 0;index < data.length;index++) {
var options = data[index].option;
var position = index + 1;
width[index] = new Array();
for (var keys = 0; keys < options.length; keys++) {
width[index][keys] = options[keys].votes;
}
}
there is no error in any browser.
Related
when i write js,i meet with some wrong about SyntaxError,the following is `part of my code
function loadData() {
tree = new dTree('tree');
tree.add(0, -1, '请选择父类')
$.ajax({
url : "${ctxPath}/type/list",
dataType : 'text',
type : 'get',
async : false,
success : function(data) {
var obj = JSON.parse(data);
for (var i = 0; i < obj.length; i++) {
tree.add(obj[i].id, obj[i].pid, obj[i].name,
'javascript:setSrcValue(/''+ obj[i].name + '/',/''+ obj[i].pid+ '/')'
);
}
var srcElement = null;
var valueElement = null;
showTree =function (item,valueId){
srcElement = window.event.srcElement;
valueElement = document.getElementById(valueId);
var x = getLeft(item);
var y = getTop(item) + item.offsetHeight;
var w = item.offsetWidth;
blockDTree(x,y,w);
}
setSrcValue=function (text,value){
srcElement.value = text;
valueElement.value = value;
hiddenDTree();
}
But my error is : Uncaught SyntaxError: missing ) after argument list.I don't know how to modify it? what's wrong with my code? what's the reason? #Jaromanda X
老铁,格式化下代码,你就可以从格式上看到问题所在了,最好用 ide,可以直接显示错误
try template string with backticks `.
for (var i = 0; i < obj.length; i++) {
tree.add(obj[i].id, obj[i].pid, obj[i].name,
`javascript:setSrcValue('${obj[i].name}' , '${obj[i].pid}')`);
}
I have an ajax function that returns a shorturl of an url from a textarea.
When I want to replace the shorturl by the actual url in the text area by using replace, the code not work. this is my implementation
Ajax function:
function checkUrl(text) {
var bit_url = "";
var url = text;
var username = "o_1i42ajamkg"; // bit.ly username
var key = "R_359b9c5990a7488ba5e2b0ed541db820";
return $.ajax({
url: "http://api.bit.ly/v3/shorten",
data: {
longUrl: url,
apiKey: key,
login: username
},
dataType: "jsonp",
async: false,
success: function(v) {
bit_url = v.data.url;
}
});
}
and a function that call the checkurl function is implemented as follow
$("#urlr").change(function() {
var text = $("#Pushtype_message").val();
var c = "";
var msgtext = "";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var MsgStr = $("#Pushtype_message").val();
var Arr = text.split(" ");
urllist = new Array();
urluri = new Array();
i = 0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest = urlRegex.test(txtStr);
if (urltest) {
urllist[i] = txtStr;
}
}
for (var i = 0; i < urllist.length; i++) {
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result) {
var response = (result.data.url);
console.log(response);
MsgStr.replace(urllist[i], response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
});
In my text area I put this text:
test utl function https://www.google.Fr test success
and I get in my console the following result
main.js http://bit.****
main.js test utl function https://www.google.Fr test success
As you see, the function return an urlshortner but the initial text still the same. My expected result is: test utl function http://bit.l**** test success, but this don't work.
When working with textarea you can simply replace their text.
$("#Pushtype_message").text(MsgStr);
You need the assign the new value to MsgStr
for(var i=0; i<urllist.length; i++){
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result){
var response=(result.data.url);
console.log(response);
MsgStr = MsgStr.replace(urllist[i],response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
i is defined outside your for loop and used inside it urllist[i]=txtStr; but its value is never assigned, it's alaways = 0:
i=0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest=urlRegex.test(txtStr);
if(urltest)
{
urllist[i]=txtStr;
}
}
I found the solution about my problem,
I affect urllist[j] to a new variable text, because in the checklist function urllist[j] return an undefined value.
var j=0;
for(j; j<urllist.length; j++){
var text=urllist[j];
checkUrl(urllist[j]).done(function(result){
var response=result.data.url;
console.log(urllist[j]);
MsgStr1 = MsgStr.replace(text,response);
console.log(MsgStr1);
$("#Pushtype_message").val(MsgStr1);
});
}
});
I have an DevExpress Mvc token extension, where the user will insert several items.
Using javascript I send the items to the controller, which is working fine.
My function look like this:
$(function() {
$("#btnSave").click(function () {
var name = window.ComboBox.GetValue();
var i;
var team = new Array();
var tokens = window.tokenBox.GetTokenCollection();
for (i = 0; i < tokens.length; i++) {
team.push(tokens[i]);
}
var s = new Array();
var ss = window.tokenBox2.GetTokenCollection();
for (i = 0; i < ss.length; i++) {
s.push(ss[i]);
}
var w = new Array();
var ww = window.tokenBox3.GetTokenCollection();
for (i = 0; i < ww.length; i++) {
w.push(ww[i]);
}
var o = new Array();
var oo = window.tokenBox4.GetTokenCollection();
for (i = 0; i < oo.length; i++) {
o.push(oo[i]);
}
var t = new Array();
var tt = window.tokenBox5.GetTokenCollection();
for (i = 0; i < tt.length; i++) {
t.push(tt[i]);
}
$.ajax({
type: "post",
url: '#Url.Action("Action","Controller")',
data: { name:name, team:team, s:s, o:o, w:w, t:t },
beforeSend: function () {
window.loadingPanel.Show();
},
success: function (response) {
$("#mainAjax").html(response);
window.loadingPanel.Hide();
}
});
});
});
I want to use a function, to get the items from token and put them in an array (not repetitive code like above), something like this:
function GetTokenItems(token) {
var list = new Array();
var el = document.getElementsById(token);
var tokens = el.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
This function is not working, error says:
Uncaught TypeError: document.getElementsById is not a function
How can I pass the Id of the tokenBok like argument in a function, or/and what is wrong with my function?
**Edit:**
I made the correction document.getElementById and now I get the error:
Uncaught TypeError: el.GetTokenCollection is not a function
Should be document.getElementById(id):
Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.
document.getElementById(...)
// ^ without s
I found the answer of my issue, maybe will be helpfull for others!
For Devexpress mvc extensions is enough to use the name of the extension like argument, no need to look for him with document.getElementById, so my function is working like this:
function GetTokenItems(token) {
var list = new Array();
var tokens = token.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
now I can call this function like this:
var team=GetTokenItems(tokenBox); and is working!!!
I'm trying to send some data in an Array via AJAX to save it to the database, I build the array this way:
$( "#saveordering" ).button().click(function( event ) {
event.preventDefault();
var data = document.getElementById('tabs');
var categories = data.getElementsByTagName("div");
var categoryArray = new Array();
for (var i=0; i < categories.length; i++) { //Loop door de categoriëen
var category = categories[i];
var categoryId = category.getAttribute('id');
categoryArray[i] = new Array();
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'] = new Array();
var forums = category.getElementsByTagName("li");
for (var j=0; j < forums.length; j++) { //Loop door de forums
var forum = forums[j];
var forumId = forum.getAttribute('id');
categoryArray[i]['forums'][j] = new Array();
categoryArray[i]['forums'][j]['id'] = forumId;
}
}
$.ajax({
type: 'POST',
url: "ajax/updateboardorder.php",
dataType: 'json',
data: {ldelim}"categories" : categoryArray{rdelim} ,
success: function(data) {
}
});
});
But nothing is send, when I do a var_dump($_POST) in PHP I'm getting:
array (size=0) empty
What am I doing wrong?
Look at this code
categoryArray[i] = new Array();
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'**strong text**
Um, that is not an "array", you are making an associative array
categoryArray[i] = {};
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'] = {};
or
categoryArray[i] = {
"id" : categoryId,
"forums" : {}
};
You want an object. Same where you do it later in the code with forums.
This is what's going on to your array:
var a = new Array();
a['id'] = 123;
JSON.stringify(a); // []
a; // []
a.length; // 0
a.id; // 123
You are trying to use the array like a primitive object:
var o = {};
o.id = 123;
JSON.stringify(o); // {"id":123}
The function below should return an array of objects with this structure:
TopicFrequency = {
name: "Chemistry", //This is dependent on topic
data: [1,2,3,4,5,6,7,8,9,10,11,12] //This would be real data
};
so when I do this:
myData = this.getChartData("line");
it should return two objects:
{name : "Chemistry", data : [1,2,3,4,51,12,0,0, 2,1,41, 31]}
{name : "Math", data : [0,0,41,4,51,12,0,0, 2,1,41, 90]}
so when I do console.log(myData); it's perfect, returns exactly this.
However when I do console.log(myData[0].data) it returns all 0s, not the values. I'm not sure what this issues is known as, and my question is simple what is this problem known as?
Here is the full function. Somethings were hardcoded and other variables (notable server and queryContent) removed. Those parts worked fine, it is only when manipulated/retreiving the returned array's values that I run into problems. Note this is async. so not sure if that is also part of the problem.
getChartData: function (chartType) {
var TopicsFrequencyArray = new Array();
timePairs = this.newIntervalSet("Month");
topicList = new Array("Chemistry", "Math");//Hard coded for now
var queryCopy = {
//sensitive information
};
for (i = 0; i < topicList.length; i++) {
var TopicFrequency = {
name: null,
data: this.newFilledArray(12, 0)
};
j = 0;
TopicFrequency.name = topicList[i];
while (j < timePairs.length) {
queryCopy.filter = TopicFrequency.name;
//additional queryCopy parameter changes made here
var request = esri.request({ url: server, content: queryCopy, handleAs: "json", load: sucess, error: fail });
j = j + 1;
function sucess(response, io) {
var topicCountData = 0;
query = esri.urlToObject(io.url);
var dateString = query.query.fromDate.replace("%", " ");
dateString = dateString.replace(/-/g, "/");
dateString = dateString.split(".");
date = new Date(dateString[0]);
dojo.forEach(response.features, function (feature) {
if (feature.properties.count > 0) {
topicCountData = feature.properties.count;
}
TopicFrequency.data[date.getMonth()] = topicCountData;
});
}
function fail(error) {
j = j + 1;
alert("There was an unspecified error with this request");
console.log(error);
}
}
TopicsFrequencyArray.push(TopicFrequency);
}
},