1

我对 jQuery 和 ajax 完全陌生。目前,我正在尝试从我将语句发布到 .php 文件以执行语句的 javascript 文件在我的本地 sql 服务器上创建一个表。

.js 文件:

function executeStatement(sqlStatement){
    $.ajax({
      type: "post",
      data: sqlStatement,
      cache: false,
      url: "api.php",
      dataType: "text",
      error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
      },
      success: function ()
      {
        alert ("Success!!");
      }
    });
  }

.php 文件:

  require_once('PhpConsole.php');
  PhpConsole::start();
  debug('HERE!!!');

  $sqlStatement = $_POST['sqlStatement'];

  $host = "*****";
  $user = "*****";
  $pass = "*****";
  $databaseName = "db_user_data";

  // Create connection
  $con = mysqli_connect($host, $user, $pass, $databaseName);

  // Check connection
  if (mysqli_connect_errno($con)){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  else{
    $con->query($sqlStatement);
    header('Location: success.php');  
  }

我使用 PHP 控制台来调试 .php 文件,但在这种情况下,即使是第一个日志“这里!!!” 没有打印到控制台,所以我想知道它是否到达了这个 .php 文件。无论如何,success即使数据库中没有更改,也会到达 executeStatement 方法中的事件并打印“成功”。顺便说一下,.php 文件也在本地服务器上执行。有人知道问题出在哪里吗?

提前致谢

4

1 回答 1

2

您的 PHP 代码中的“$pass”变量有一个错字:

require_once('PhpConsole.php');
PhpConsole::start();
debug('HERE!!!');

$sqlStatement = $_POST['sqlStatement'];

$host = "*****";
$user = "*****";
**$pass = "*****";**
$databaseName = "db_user_data";

// Create connection
$con = mysqli_connect($host, $user, $pass, $databaseName);

// Check connection
if (mysqli_connect_errno($con)){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
  $con->query($sqlStatement);
  header('Location: success.php');  
}

EDIT: Here is my revised JS code - this works perfectly for me as I am able to pass the code from an AJAX call to the PHP code and back. Try this:

var sqlStatement = "sqlStatement=SQLSTATEMENTHERE";
$.ajax({
  type: "POST",
  data: sqlStatement,
  cache: false,
  url: "api.php",
  success: function ()
  {
    alert ("Success!!");
  }
});

Place the variable outside of your function and the ajax call inside to replace the old one. As for the PHP, i'll check that out in a second.

于 2013-03-30T12:46:01.100 回答