数据库中不同div的每一行

时间:2014-05-16 13:00:23

标签: javascript html

我尝试为数据库中的每一行创建一个不同的div。它只在我尝试运行它时不起作用,它只给我两个字母。我检查了我的PHP,它运行正常。

var request = new XMLHttpRequest;
request.open('GET' , 'myurl', false);
request.send();
console.log(request);

if (request.status == 0) console.log(request.responseText);

var firstname, lastname;
var obj = JSON.parse(request.responseText);
console.log(obj);

for (var i = 0; i<obj.length; i++){
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    console.log(firstname,lastname);

    var divElement = document.createElement("div");  
    divElement.id = "myDiv";  

    divElement.className = "myDivClass";  
    divElement.innerHTML = firstname[i] + " " + lastname[i];
    document.body.appendChild(divElement);    
}

2 个答案:

答案 0 :(得分:0)

您似乎只根据循环编写元素。

你为什么要这样做

 divElement.innerHTML = firstname[i] + " " +  lastname[i];

何时需要

 divElement.innerHTML = firstname + " " +  lastname;

答案 1 :(得分:0)

var request = new XMLHttpRequest;
request.open('GET', 'myurl', false);
request.send();
console.log(request);

console.log(request.responseText);
var firstname, lastname;

var obj = JSON.parse(request.responseText);
console.log(obj);

for (var i = 0; i<obj.length; i++) {
  firstname       = obj[i].Firstname;
  lastname        = obj[i].Lastname;

  console.log(firstname,lastname);


  var divElement = document.createElement("div");  
  divElement.id = "myDiv";  

  divElement.className = "myDivClass";  

  divElement.innerHTML = firstname + " " +  lastname;

  document.body.appendChild(divElement);  
}

试试这个。