2010-06-07 22 views
2

我有一個表單,當您提交它時,它會通過ajax將驗證數據發送到另一個php腳本。驗證錯誤在我的表單中以div形式回顯。如果驗證通過,則還會返回成功消息。如何在Ajax響應中調用Javascript? IE:成功時關閉表格div

問題是表單在提交和成功驗證後仍然顯示。我想在成功後隱藏div。

所以,我寫了這個簡單的CSS方法,當從表單顯示的頁面調用時,它可以正常工作。

問題是,我似乎無法通過返回的代碼調用隱藏腳本。我可以返回HTML像

echo "<p>Thanks, your form passed validation and is being sent</p>"; 

所以,我認爲我可以簡單地迴應說

echo "window.onload=displayDiv()";
裏面的腳本標記(我不能去這裏顯示)後,另一條線......

,它會隱藏表格div。

它不起作用。我假設問題是JavaScript正在返回不正確,不被瀏覽器解釋...

如何通過我的驗證腳本返回的數據調用我的'隱藏'腳本頁面上?我可以回顯文本,但腳本調用無效。

謝謝!

這是與表單頁面上的腳本...

我可以把它展現的東西,如/隱藏的onclick =「displayDiv()」,而在窗體上,但我不希望用戶調用這個...當我寫的結果返回到div它被稱爲一個成功驗證的結果...

<script language="javascript" type="text/javascript"> 
    function displayDiv() 
    { 
     var divstyle = new String(); 
     divstyle = document.getElementById("myForm").style.display; 
     if(divstyle.toLowerCase()=="block" || divstyle == "") 
     { 
      document.getElementById("myForm").style.display = "none"; 
     } 
     else 
     { 
      document.getElementById("myForm").style.display = "block"; 
     } 
    } 
    </script> 

PS:我使用的是mootools.js庫形式驗證如果這對於語法來說很重要。

該AJAX調用是:

 
window.addEvent('domready', function(){ 
$('myForm').addEvent('submit', function(e) { 
new Event(e).stop(); 
var log = $('log_res').empty().addClass('ajax-loading'); 
this.send({ 
update: log, 
onComplete: function() { 
log.removeClass('ajax-loading'); 
} 
}); 
}); 
}); 

股利ID日誌是AJAX調用迴文本(驗證錯誤和成功消息)和裝載圖形顯示

+0

請向我們展示您的AJAX調用。 – SLaks 2010-06-07 16:33:08

+0

編輯原始帖子以顯示它... – 2010-06-07 17:32:46

回答

0

你的AJAX調用應該有一個「成功」的回調。看起來你可以簡單地在該回調中調用​​。

另請注意,var divstyle = new String();行是不必要的。字符串在JavaScript中是不可變的,所以你正在創建一個空字符串對象,它仍然在下面的行中未被引用。簡單地聲明,當你從document.getElementById()分配給它的變量:

var divstyle = document.getElementById("myForm").style.display; 
0
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 

//Since your making php do the validation, there would be two cases, 
//the first case is that the php script is not echoing any thing on success, and 
//the other case is that its echoing the error massages which will be assignedxmhttp.responseText 
//so we need to check that xmlhttp.resposeText has been asigned a value. 

    if(xmlhttp.resposeText){ 
     document.getElementById(displayContainers_id).innerHTML=xmlhttp.responseText; 
    } 
} 
+0

好的...那麼這是去哪裏?在我的聯繫表單頁面的標題中?我是否將它包裝在腳本標籤中?我如何告訴它影響到div的問題,我需要我的小CSS隱藏腳本? – 2010-06-07 17:19:45

1

這是How to make JS execute in HTML response received using Ajax?,我所提供的選擇的解決方案的副本。

var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html"; 
var reScript = /\<script.*?>(.*)<\/script>/mg; 
response = response.replace(reScript, function(m,m1) { 
    eval(m1); //will run alert("foo"); 
    return ""; 
}); 
alert(response); // will alert "htmlhtml"