2

我在这里这里使用 Tizag 教程。我稍微修改了代码,如下:

订单.html:

<html>
<body>
<script type="text/javascript">
<!-- 
function createRequest() {
    try {
      request = new XMLHttpRequest();
      //alert("Request is XMLHttp");
    } catch (tryMS) {
      try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
        //alert("Request is ActiveX1");
      } catch (otherMS) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
          //alert("Request is ActiveX2");
        } catch (failed) {
          request = null;
        }
      }
    }
    return request;
  }
function ajax1(){
    ajaxRequest = createRequest();
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            //alert("Request.readyState is 4");
            var ajaxDisplay = document.getElementById('ajaxDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }
    var age = document.getElementById('age').value;
    var wpm = document.getElementById('wpm').value;
    var sex = document.getElementById('sex').value;
    var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
    ajaxRequest.open("GET", "ajaxEx1.php" + queryString, true);
    ajaxRequest.send(null); 
}
//-->
</script>

<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajax1()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

以及被称为 ajaxEx1.php 的页面:

<?php
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "abcd";
$dbname = "test01";
mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname) or die(mysql_error());
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
    $query .= " AND ae_age <= $age";
if(is_numeric($wpm))
    $query .= " AND ae_wpm <= $wpm";
    //Execute query
$qry_result = mysql_query($query) or die(mysql_error());
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
while($row = mysql_fetch_array($qry_result)){
    $display_string .= "<tr>";
    $display_string .= "<td>$row[ae_name]</td>";
    $display_string .= "<td>$row[ae_age]</td>";
    $display_string .= "<td>$row[ae_sex]</td>";
    $display_string .= "<td>$row[ae_wpm]</td>";
    $display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

这很好用而且非常简单。但是,我注意到在这个示例中,查询本质上是由 Javascript 请求的,在 MVC 模式中被视为 View 元素。在实际的 MVC 站点中这仍然是一个好习惯吗?视图是否会将一些参数发送到一个文件,该文件将运行查询本身或将其传递给 DAO 并接收响应?

如果不是,如果上面是 MVC 站点的一部分,那么 Ajax 部分将如何重新组织?

4

6 回答 6

1

如果是我,并且我在一个足够大的站点上工作,它需要通过 MVC 模式进行模块化,我肯定会将 ajax 内容提取到模型对象而不是视图中。像 Backbone.js 这样的框架在这​​方面工作得非常好,因为模型有内置的 ajax 处理并且会为你来回填充数据。

如果你想自己做,你可以创建一个模型对象,它只将数据(而不是 DOM 元素)作为参数并为你返回数据。

function AjaxModel() {

    this.get = function(age, wpm, sex, callback) {

        ajaxRequest = createRequest();
        ajaxRequest.onreadystatechange = callback;

        var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
        ajaxRequest.open("GET", "ajaxEx1.php" + queryString, true);
        ajaxRequest.send(null);
    } 
}

那么你可以这样称呼它:

var ajaxM = new AjaxModel();
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
ajaxM.get(age, wpm, sex, onComplete);

function onComplete(r) {
    /// your ajax complete method
}

如果您的网站足够大,Backbone.js那么在我看来,包含一个类似框架是非常值得的。

作为旁注,MVC 模式是如何分离逻辑的模型,但它并不完美。我经常发现自己创建了许多视图和模型,但很少有控制器。视图逻辑与 javascript 中的控制非常相关,所以我经常发现它们并不需要。我会做对您最有意义的事情,同时确保至少您的数据与其他所有数据分开。

祝你好运。

于 2012-12-10T18:27:58.800 回答
1

只要您知道为什么要这样做以及这样做的结果会怎样,一切都会好起来的;)。但是,这肯定不是最佳实践。

在 MVC 应用程序中,通常有很多事情在“后台”进行。每个请求都有它的生命周期,这个生命周期的外观取决于它所构建的代码库。

如果您选择不使用此链,您也将失去它带来的好处。它可能涉及(由您或其他人)注册的各种钩子和插件,以使系统作为一个整体工作。它还可能涉及提供系统安全性,例如集中式 ACL 逻辑。

我建议你使用控制器,它反过来从模型中请求数据。然后,这些数据可以从控制器直接发送到客户端(作为 JSON 或 XML),或者发送到在客户端处理数据之前格式化数据的视图。但我喜欢使用 JSON。

并且,JavaScript 应该与标记 (HTML) 分开,并放在一个 .js 文件中。

祝你好运

于 2012-12-11T01:58:23.113 回答
1

在 MVC 中,您通常发布到一个控制器,该控制器构造传递给视图以显示的模型。

You are using AJAX calls to update parts of your view dynamically without reloading the complete view. It is is completely fine to construct your query inside your JavaScript code. If you're concerned about separating model and view code, you may want to look at KnockoutJS for client side (JavaScript) MVVM pattern implementation.

于 2012-12-11T04:17:45.110 回答
0

I would, never ever, make calls into a database directly with an ajax request.

于 2012-12-11T13:12:28.313 回答
0

If you're using MVC, the good approach is to use it in the entire app.

So, when doing an ajax request, build the query string or pretty url acording to your framework needs, implement everything as you would use a normal view (View <- Controller <- Model) and just format the view to return the AJAX stuff (partial HTML, JSON, XML, or whatever).

Usually this may be done by just not using a template with the view.

于 2012-12-11T15:41:53.790 回答
0

I think it is ok to put you ajax code (make it generic and reusable depending on your needs) in a separate javascript file that you can include in the view that needs that kind of ajax call.

You should implement an ajax controller, that will process you ajax requests and just send the response? if it is data you just return data using json. this is how I am doing it with Zend framework.

Take a quick look at this Implementing OOP PHP with AJAX, MVC?

于 2012-12-11T16:24:20.753 回答