了解ajax正在做什么

时间:2015-04-30 03:28:03

标签: javascript php mysql ajax azure

作为课程的一部分,我必须构建一个连接到数据库的Web应用程序,全部托管在azure上并实现REST api。 我已经设置了一个MySQL数据库,现在我正在努力完成我的讲师给出的示例代码,以便将其调整到我当前的项目中。只有我跟着它有些麻烦。所需的结构是index.html有一个按钮,当按下它时,对NameWebService的调用使用ajax连接到php文件,然后处理数据库连接和数据集合。 然而,没有任何东西从数据库返回(并且无法从webmatrix调试php,我不能100%确定连接是否已建立)。

非常感谢任何帮助。

NameWebService.js

var year;
var gender;

function SetValues() {
    year = document.getElementById('Year').value;
    gender = document.getElementById('Gender').value;
}

function getNames(year, gender)
{
    //alert(year + '\n' + gender);
    $.ajax({
        url: '/Name',
        type: 'GET',
        data: 'table='+year,
        datatype: 'json',
        success: function (data) {
            alert('Data is:\n'+data)
           createNamesTable(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
           alert(jqXHR + '\n' + textStatus + '\n' + errorThrown);
        }
    });
}

function createNamesTable(Names)
{
    var strResult = '<div class="col-md-12">' + 
                    '<table class="table table-bordered table-hover">' +
                    '<thead>' +
                    '<tr>' +
                    '<th>Rank</th>' +
                    '<th>Name</th>' +
                    '<th>Change Since Last Year</th>' +
                    '</tr>' +
                    '</thead>' +
                    '<tbody>';
    $.each(Names, function (Rank, Name){                        
        strResult += "<tr><td>" + Name.Rank + "</td><td> " + Name.Name + "</td><td>" + Name.Change + "</td>";
    });
    strResult += "</tbody></table>";
    $("#allNames").html(strResult);
}

调用PHP并因此调用数据库,收回数据并从中创建表。

NameRestService.php

<?php    
    require "RestService.php";
    require "Name.php";

class NameRestService extends RestService 
{
  private $Domain = 'domain';
  private $User = 'username';
  private $Password = 'password';
  private $Database = 'database';
  private $Names;

  public function __construct() 
  {
    parent::__construct("Name");
  }

  public function performGet($url, $parameters, $requestBody, $accept) 
  {
    $this->initialiseData($_GET['table']);
    echo json_encode($this->Names);
  }

  private function initialiseData($year)
  {
      $this->Names = [new Name("100000","Test","-23124324"),new Name("100001","Testtwo","-24")];
  }
}
?>

并且RestService的扩展提供了我们想要的特定功能。尽管明确地只将Names设置为一个条目,但它总是返回空。我也不确定数据库是否正确连接。

RestService.php

<?php

class RestService 
{
  private $supportedMethods;
  private $apiStringToMatch;

  public function __construct($apiStringToMatch) 
  {
    $this->supportedMethods = "GET, PUT, POST, DELETE";
    $this->apiStringToMatch = $apiStringToMatch;
  }

  public function handleRawRequest($_SERVER, $_GET, $_POST) 
  {
    $url = $this->getFullUrl($_SERVER);
    $method = $_SERVER['REQUEST_METHOD'];
    $requestBody = file_get_contents('php://input');

    if (isset($_GET['q']))
    {
        $parameters = explode("/", $_GET['q']);
        if (strlen($this->apiStringToMatch) > 0 && count($parameters) > 0)
        {
            if (strcmp($this->apiStringToMatch, $parameters[0]) != 0)
            {
                $this->notImplementedResponse();
                return;
            }
        }
    }
    else
    {
        $parameters = array();
    }
    if (isset($_SERVER['HTTP_ACCEPT'])) 
    {
      $accept = $_SERVER['HTTP_ACCEPT'];
    }
    else 
    {
      $accept = "";
    }
    $this->handleRequest($url, $method, $parameters, $requestBody, $accept);
  }

  protected function getFullUrl($_SERVER) 
  {
    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    $location = $_SERVER['REQUEST_URI'];
    return $protocol.'://'.$_SERVER['HTTP_HOST'].$location;
  }

  public function handleRequest($url, $method, $parameters, $requestBody, $accept) 
  {
    switch($method) 
    {
      case 'GET':
        $this->performGet($url, $parameters, $requestBody, $accept);
        break;
      default:
        $this->notImplementedResponse();
    }
  }

  protected function notImplementedResponse() 
  {
    // 501 Not Implemented 
    header('Allow: ' . $this->supportedMethods, true, 501);
  }


  protected function methodNotAllowedResponse() 
  {
    // 405 (Method Not Allowed)
    header('Allow: ' . $this->supportedMethods, true, 405);
  }

  protected function notFoundResponse()
  {
    header("HTTP/1.1 404 Not Found");
  }

  protected function noContentResponse()
  {
    header("HTTP/1.1 204 No Content");
  }

  // Override the following methods to provide the appropriate functionality

  public function performGet($url, $parameters, $requestBody, $accept) 
  {
    $this->methodNotAllowedResponse();
  }
}
?>

Rest api的基类,列出了基础。我无法判断ajax请求是来到这里还是来到NameRestService ......

Name.php

<?php
class Name
{
    public $Rank;
    public $Name;
    public $Change;

    public function __construct($rank, $name, $change)
    {
        $this->Rank = $rank;
        $this->Name = $name;
        $this->Change = $change;
    }

    public function GetRank()
    {
        return $this->Rank;
    }

    public function GetName()
    {
        return $this->Name;
    }

    public function GetChange()
    {
        return $this->Change;
    }
}
?>

我们数据的基础对象存储为。

修改

我一直在与一些同行交谈,我们已经开始明白需要做些什么。该站点正在使用web.config将请求重新路由到api.php,然后api.php初始化其余的php。

我还为此阶段削减了很多非重要代码并更新了上述内容以进行匹配。 web config和api.php是这样的:

api.php

<?php
    require "NameRestService.php";

$service = new NameRestService();
$service->handleRawRequest($_SERVER, $_GET, $_POST);
?>

的web.config

<?xml version="1.0"?>
<configuration>
    <system.webServer>
       <handlers>
         <remove name="PHP53_via_FastCGI" />
         <add name="PHP53_via_FastCGI" path="*.php"
              verb="GET, PUT, POST, DELETE, HEAD" 
              modules="FastCgiModule" 
              scriptProcessor="D:\Program Files (x86)\PHP\v5.3\php-cgi.exe"
              resourceType="Either" requireAccess="Script" />
       </handlers>
       <rewrite>
         <rules>
            <rule name="Rule" stopProcessing="true">
                <match url="^(.*)$" ignoreCase="false" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
                </conditions>
                <action type="Rewrite" url="api.php?q={R:1}" appendQueryString="true" />
            </rule>
          </rules>
        </rewrite>
    </system.webServer>
</configuration>

问题是,每当我尝试访问PHP函数时,我都会收到内部服务错误。

2 个答案:

答案 0 :(得分:1)

要监控和调试AJAX调用,请使用浏览器的开发人员工具(按F12)。然后,您将看到“网络”选项卡,您可以在其中查看服务器的所有流量,包括参数和响应数据。在某些浏览器中,您有一个XHR子选项卡,它仅过滤AJAX请求(如果您有大量图像,则非常有用)。

答案 1 :(得分:0)

不应该这个

$.ajax({
    url: '/NameRestService.php',

{{1}}