2013-02-05 128 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'); 
} 
相關問題