2013-02-05 132 views
1

我想在ajax中插入div标签,但我无法弄清楚如何。到目前为止,这是我的代码:如何在Ajax中添加DIV标签

function userLogin(){ 
var email = $("#login_username_text").val(); 
var password = $("#login_password_text").val(); 
var login_url = connect_url+'retrieveUser.php?email='+email+"&password="+password; 

$.ajax({ 
     type: 'GET', 
     url: login_url, 
     async: true, 
     jsonpCallback: 'userCallback', 
     contentType: "application/json", 
     dataType: 'jsonp', 
     success: function(json) { 
      is_logged = (json[0].logged==0)?false:true; 
      alert(is_logged); 
      alert(email); 
      alert(password); 

      if(is_logged==false){ 
       alert ("Invalid Username and Password"); //I want to change 
//this into a div tag so that it will be displayed on the page itself and so that 
//I can add CSS codes here 
      } 
     }, 
     error: function(e) { 

     } 
}); 
} 

我试过document.getElementById('login_invalid').innerText = 'Invalid Username and Password.';但没有工作...任何想法?

谢谢!

+0

你的网页上是否有ID为login_invalid的div? –

+0

console.log(is_logged),让我们知道结果。编辑:由于您已经使用jQuery,使其$(“#login_invalid”)。html(“无效”);而不是使用getElementById。 – KBN

+0

我会建议[寻找一些基本的DOM操作教程](https://www.google.nl/search?q=dom+manipulation+tutorial+jquery) – Cerbrus

回答

0

innerText不是普遍支持的属性。尽管更标准化的textContent对于阅读内容非常有用,但最好使用innerHTML来替换div的内容。

假设你的DIV存在,你应该使用

document.getElementById('login_invalid').innerHTML = 'Invalid Username and Password.'; 

,或者你明明使用jQuery

$('#login_invalid').html('Invalid Username and Password.'); 
+0

它现在工作...谢谢! **谢谢大家! :) – ninpot18

1

尝试

$("<div/>", { 
    "class": "test", 
    text: "Invalid Username and Password", 
    }).appendTo("body"); 
0

可以追加div标签,并添加类对此,它会起作用。如果你想添加Id到这个元素,你可以使用.attr('attribute_name','attribute_value')如下:

if(is_logged==false){ 
     $('body').append('<div>Invalid Username and Password</div>').addClass("error").attr('id', 'login_invalid'); 
} 
相关问题