【发布时间】:2014-05-26 22:11:51
【问题描述】:
我通过使用 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 调用中返回完整列表(将其放入带有 json_encode 的 json 对象中),或者您可以只返回添加的项目,然后附加它。由你决定。在您的 JS 中嵌入 php 将不起作用,因为 php 只会在页面加载时运行一次
-
@user574632 非常感谢您对使用 JSON 的建议,我听说过它,但不知道它在哪里可能有用。感谢您的建议,我现在已经查找了它,并尝试在我的 responseText 中使用它!谢谢!
-
没问题,坚持使用 JSON,相比之下 XML 很痛苦。
标签: javascript php ajax templates httprequest