簡體   English   中英

使用PHP更新數據庫后視圖的no-jquery ajax更新

[英]no-jquery ajax update of view after database update using PHP

我通過在PHP和MySQL中構建站點來學習MVC和Ajax。 我制作了一個新的控制器方法來處理ajax,現在可以從我的Ajax HTTPRequest成功更新數據庫。 收到響應后,我可以通過使用諸如“ Hello”之類的javascript字符串替換部門的當前內容來更新部門,但我不知道如何用更新的數據庫數據替換內容。 如何正確更新部門? 現在,我想在沒有JQuery的情況下執行此操作,並且不使用PHP框架。 部門中的數據是成員去過的地方的列表。 在Ajax之前,列表在頁面加載時發送到“視圖”:

//this is controller->index()
public function index() {
    //the properties will be pulled up from the db as neccessary so we need to set them first
    $this->member->setMembername();
    $this->member->setMemberProfile();
    $this->member->setMyPlacesList();
    $this->member->setMemberData(); //puts the above data into one array for convenience
    $this->view->setData($this->member->getmemberData());
    $this->view->render('welcomepage/index'); //builds the view with the data
}

現在在我的ajax調用中,我的控制器告訴成員模型更新該成員所在的位置列表:

public function AjaxAddVisit() {
    $details['sitename'] = $_POST["sitename"];
    $details['datetime'] = date("Y-m-d H:i:s");
    $details['comments'] = $_POST['comments'];
    $this->member->addMemberVisit($details); This successfully adds the place to the database.  
    //I suppose I should now do something like ?
    //$this->member->setMyPlacesList();
    //$this->member->setMemberData();
    //$this->view->setData($this->member->getmemberData());//this would update the views data
}

我現在想從Ajax代碼中修改視圖中的列表,但不知道如何做,我是否要執行以下操作,我只是將php代碼嵌入這樣的javascript字符串中?

function AddVisitResponse() {
    if (myReq.readyState == 4) {
        if(myReq.status == 200) {
        var phpString = "<?php echo $this->data['myPlacesList'][0][1] ?>";
        document.getElementById('myPlacesList').innerHTML = phpString;
        //this would just print out one element of the list, but just for example
        } else {
        alert("got no response from the server");
        }
    }
} 

上面的輸出是這樣的:myPlacesList'] [0] [1]?>所以我認為一定有問題。 似乎我根本無法發送帶有php代碼的字符串,即使我回顯“ hello”也不起作用。 如何正確更新部門? 我應該使用XML在php控制器方法中格式化字符串嗎? 非常感謝,這是我在這里的第一個問題,任何幫助將不勝感激!!!

很難看到完整的ajax代碼( myReq變量的范圍是什么?),但是從服務器發送回ajax腳本的任何內容都應該可以通過myReq.responseText訪問。

因此,您需要將函數修改為:

function AddVisitResponse() {
    if (myReq.readyState == 4) {
        if(myReq.status == 200) {
            document.getElementById('myPlacesList').innerHTML = myReq.responseText;
        } else {
            alert("got no response from the server");
        }
    }
}

請注意,您運行javascript函數時,頁面加載的javascript中包含的所有php都已被處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM