2014-06-30 22 views
0

我有一個ajax調用一個php腳本,它在服務器上運行一些東西。當這完成後,我想讓php調用一個javascript函數。爲此,我使用了這個。html onload在Internet Explorer中的Ajax調用後沒有觸發,

//This line works in chrome and firefox. 
echo "<style onload='test()'></style>"; 
//this one doesnt work after an ajax call. 
echo "<script type='text/javascript'>test()</script>"; 

此行在Chrome和Firefox中運行並觸發,但不在Internet Explorer中。

所以我的問題是,有沒有解決方案或替代呢?
根據ajax調用的結果,是否有方法在ajax調用後調用新的javascript函數? (不只是成功或失敗)

我解釋我的系統多一點額外的信息。我在會話中存儲了很多我的數據。

我得到我的代碼,並從這個例子的額外或無用的代碼剝離它,在這個拼寫錯誤,解析錯誤或其他可能發生的語法錯誤這不是問題雖然。

//Index.php 
<head><script src='location' type='text/javascript'></script></head> 
<body> 
    <div id='container'> 
     <div id='head'></div> 
     <div id='content'></div> 
    </div> 
    <div id='hidden'></div> // this div is hidden for js feedback 
    <script type='text/javascript'>loadContent();</script> 
</body> 

//javascript file 
function loadContent(){ 
    //my ajax function works it requires 3 variables 
    //url to php, div that will be changed, array with post variables. 
    Ajax("urltophp", "hidden", Array("")); 
} 

function loadHome(){ 
    Ajax("urltophp2", "head", Array("headhome")); 
    Ajax("urltophp2", "cont", Array("conthome")); 
} 

function loadLogin(){ 
    Ajax("urltophp2", "head", Array("headlogin")); 
    Ajax("urltophp2", "cont", Array("contlogin")); 
} 

function test(){ 
    alert("test"); //for testing 
} 

//then urltophp 
$ses = $_SESSION("ses"); //this is an object of class SESSION 
$timeout = $ses->getTimeout(); 
$loggedin = $ses->getLoggedin(); 
//THIS WORKS IN CHROME AND FIREFOX NOT IN IE. 
if(time() - $timeout < 3600){ //if an hour hasnt passed since last action. 
    if($loggedin){    //if user was logged in. 
     echo "<style onload='loadHome()'></style>"; 
    }else{ 
     echo "<style onload='loadLogin()'></style>"; 
    } 
} 

//urltophp2 
$p = $_POST['var1']; 
$ses = $_SESSION["ses"]; 
//used for checking if user is logged in before loading page 
//in case of cross-site scripting. left out in this example. 
$loggedin = $ses->getloggedin(); 
switch($p){ 
    case "headhome": 
    echo $homehead; //assume I loaded this from a file. 
    break; 
    case "conthome": 
    echo $conthead; //assume the same. 
    break; 
    etc. for all options. 
} 

在此先感謝kpp。

+0

我覺得'onload'不是'style'標記的屬性 –

+0

將'onload ='test()''移動到body標籤 – colburton

+0

@colburton我試過了,沒有在任何瀏覽器上工作。最大的問題是,我試圖在加載dom之後執行javascript,並且IE告訴我這是不可能的,而其他人則確定繼續前進 – kpp

回答

0

有沒有辦法在ajax調用後調用一個新的javascript函數,具體取決於ajax調用的結果?

是的。

$.get("test.php", function(data) { 
    if (data.prop === "A") { 
     foo(); 
    } else { 
     bar(); 
    } 
}); 

注:很顯然,我在這裏使用jQuery。

+0

我只是在研究這個問題,但唯一的問題是我該怎麼做該檢查就在那裏,就像我可以讓我的PHP返回像1,2或3,但仍然在一個div回聲其他的東西?或者我必須讓PHP回聲1,2,3,然後使用該結果來回顯其他東西在一個div? – kpp

+0

我不確定你的意思。要將數據從PHP傳遞到JS,您應該使用內置的'json_encode'函數。然後只是回顯功能的結果,如''。 – durrrutti

+0

我錯誤地提出了我的問題,我幾乎指''data.prop'從哪裏來。這是你在你的PHP回聲或你回報的東西。 – kpp

相關問題