ajax从mysql

时间:2015-06-08 10:46:24

标签: javascript php jquery ajax

您好我正在尝试使用ajax从服务器加载数据。这是我的js

<script>
jQuery(document).ready(function($){
$("#mc-prize").click(function(){ 
event.preventDefault();
$.ajax({
          url: "includes/prize.php",
          type: "GET",
          datatype: "text",
          data: {"num": num},
          cache: false,
          success: function(response){
                 $("#some-block").append(response);
         }
        });
});
});
</script>

这是我的prize.php文件

<?php
$host = '#';
$user = '#';
$password = '#';


if (isset($_POST['submit'])){
    $prize_email = $_POST['email'];
    $mysqli = new mysqli($host, $user, $password, $user);
    $result = $mysqli->query("SELECT * FROM prize_numbers WHERE email = '" .$prize_email. "'") or die ("Couldn't connect to database.");
    $row = $result->fetch_assoc();
   if($row['email']) {
       echo "Your num: ".$row['num'];
    } else {
       echo "No email in db";
    }

}
?>

但是当我试图从db获取一些数据时,我看到一个错误: “未捕获的ReferenceError:num未定义”

怎么了?

UPD:对不起,我的php的js是什么?我需要在数据中放置什么?

2 个答案:

答案 0 :(得分:1)

您的问题不在您的PHP中,而是在js代码中 这段代码

data: {"num": num},

变量num未在js代码

中的任何位置定义

尝试使用此代码:

<script>
jQuery(document).ready(function($){
$("#mc-prize").click(function(){ 
var some_email = ''; // DEFINE HERE THE EMAIL YOU WANT TO SEND
event.preventDefault();
$.ajax({
          url: "includes/prize.php",
          type: "POST",
          datatype: "text",
          data: {"email": some_email,"submit": 1},
          cache: false,
          success: function(response){
                 $("#some-block").append(response);
         }
        });
});
});
</script>

答案 1 :(得分:0)

未定义JQuery中的num。 数据是您要转出的参数,响应是您作为输出获得的结果。 只需替换这行代码即可  data: {"num": num}, data: "email="+email_var并添加变量email_var的实现(例如var email_var = "simplemail@mail.org")。

UPD:传递电子邮件,以便您可以在PHP中查看。

if (isset($_POST['email'])){
    $prize_email = $_POST['email'];
    $mysqli = new mysqli($host, $user, $password, $user);
    $result = $mysqli->query("SELECT * FROM prize_numbers WHERE email = '" .$prize_email. "'") or die ("Couldn't connect to database.");
    $row = $result->fetch_assoc();
   if($row['email']) {
       echo "Your num: ".$row['num'];
    } else {
       echo "No email in db";
    }