2011-02-15 110 views
2

我試圖做一些Ajax的東西,基本上,這取決於返回的文件(PHP文件)中的結果,我們在JavaScript中有不同的操作。如何根據ajax的結果執行不同的js操作?

例如,說我做了以下內容:

$.ajax({ 
    type: 'POST', 
    url: '/something.php', 
    data: 'something=something', 
    cache: false, 
    success: function(data) { 
     $('#something').html(data); 
    } 
    }); 

我的東西的div將返回的東西,如果它成功了。裏面「something.php」但是,有可能是一個if語句,像這樣:

if($_POST['something'] == 'not_something') { 

    // execute something here 

} else { 

    // do something else 

} 

的事情是,我正在執行,根據結果將是JavaScript的,而不是PHP代碼。例如,目前我可以做一些像這樣實現它:

if($_POST['something'] == 'not_something') { 

    echo '<script type="text/javascript">thissucks();</script>'; 

} else { 

    echo '<script type="text/javascript">atleastitworks();</script>'; 

} 

,但它只是看起來不正確我。有沒有更好的方式來完成這種事情?

另一種情況可能是某種類型的ajax搜索功能,根據是否有結果做不同的事情。這類事情。如何做到這一點,而不是像上面所做的那樣做一些真正的groovy inline javascript?

回答

3

您可以使用PHP的json_encode來格式化一個數組,該指令將指令返回給jQuery $.ajax()函數。像這樣的:

<?php 

if($_POST['something'] == 'not_something') { 
    echo json_encode(array('status'=>'thissucks')); 
} 

在這一點在成功的$.ajax()匿名函數對象字面看起來像這樣:

$.ajax({ 
    type: 'POST', 
    url: '/something.php', 
    date: 'something=something', 
    cache: false, 
    dataType: 'json', //this is important! 
    success: function(data) { 
     if(data['status']=='thissucks'){ 
     //do something here 
     } 
    } 
    }); 

祝您好運!

UPDATE 忘記了所有重要的數據類型屬性,使它成爲eval()的json!

+0

多數民衆贊成在相當真棒!我應該像一年前一樣問這個問題。 – willdanceforfun 2011-02-15 06:40:24

相關問題