如何通过php mvc中的javascript ajax检索数据?

时间:2015-08-18 09:12:47

标签: javascript php ajax

当我触发按钮时,我认为AJAX没有调用index.php文件。 所以我不知道$_GET['r']变量是否存在。

这是我的代码:

的index.php

<?php

require_once 'controller/controller.php';

$controller = new controller;

Controller.php这样

<?php
require_once 'model/model.php';

class controller{  
   public $model;

   public function __construct(){
      $data = null;

      if(isset($_GET['r'])){
        $this -> model = new model;
        $data = $this -> model -> getData();
      }

      require_once 'view/home.php';
     }
    }

model.php

<?php

class model{

   public function getData(){
      return 'world!';
   }
}

home.php

<!doctype html>
<html lang="en">
<head>
   <title></title>
   <meta charset="utf-8" />
   <script type="text/javascript" src="public/scripts/jscript.js"></script>
</head>
<body>
<span id="status">Status: </span><br />
<input type="text" id="data" />
<input type="submit" name="send" id="send" value="send" />
<div id="result"><?php echo $data;?></div>
</body>

jscript.js

window.onload = init;

var xmlObject = false;

function init(){
   var send = document.getElementById("send");

   xmlObject = createXMLObject();
   send.onclick = process;
}

function createXMLObject(){
   var xmlObject = false;
   if(window.XMLHttpRequest){
      xmlObject = new XMLHttpRequest();
   }else{
      xmlObject = new ActiveXObject("Msxml2.XMLHTTP");
   }

   return xmlObject;
}

function process(){
   xmlObject.open("GET", "index.php?r=1", true);
   xmlObject.onreadystatechange = function(){
      if(xmlObject.status == 200){
         if(xmlObject.readyState == 4){
            document.getElementById("status").innerHTML = "Status: Success!";
         }
      }
   }
   xmlObject.send(null);
}

0 个答案:

没有答案