2014-06-22 142 views
0

我想做一個ajax請求,允許用戶從輸入字段發送一些數據到數據庫,然後返回到輸入字段,就像評論框一樣,所以數據應該插入到數據庫中,然後顯示在無需重新加載頁面,在這裏輸入字段是我的代碼:如何在Yii中製作ajax請求?

function getHTTPObject(){ 
    if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); 
    else if (window.XMLHttpRequest) return new XMLHttpRequest(); 
    else { 
     alert("Your browser does not support AJAX."); 
     return null; 
    } 
} 


// Implement business logic  
function doWork(){  
    httpObject = getHTTPObject(); 
    if (httpObject !== null) { 
     httpObject.open("GET", "a page or a controller action" 
         , true); 
     httpObject.send(null); 
    // httpObject.onreadystatechange = setOutput; 
    } 
} 

所以,我怎麼能做出可以調用的控制器操作,而無需離開整個頁面的請求?

+0

通過向映射到控制器的'url'發出請求。 – christopher

+0

@christopher例子? –

回答

3

首先,爲了提出Ajax請求,我建議你使用jQuery。這會容易很多。

這裏是(使用jQuery)的例子:

jQuery.getJSON('/path/to/your/controller/someAction/',function(response) { 
console.log('Server reply : ',response); 
} 

在你的控制器的動作,不要忘記送輸出JSON:

public function actionSomeAction() 
{ 
    die(json_encode("This is my response")); 
} 

編輯:如果您不需要jQuery的,看到這個SO回答用於在沒有jQuery的情況下進行Ajax調用:https://stackoverflow.com/a/8567149/911718

+0

如果你只*做AJAX請求,那麼沒有必要拉下整個'jQuery'工具包。更好的做法是用香草豆做。 – christopher

+0

我同意這一點。 –

+0

這可能是值得包括鏈接到/一些示例代碼在香草JavaScript。 – christopher