如何回响警报?

我想在数据插入之前在PHP中使用Java脚本警报。我能够将数据插入数据库,但echo无法完成其工作。这可能只是一个简单的错误,但我无法发现它:(

/// Java script
/// send data for insertion
$.get("tute7_add.php",{unit_code:unit_code,unit_name:unit_name,lecturer:lecturer,semester:semester}).done(function(data){
                    alert('You have added a unit successfully!');
                });

tute7_add.php

<?php
            // I Can't send alert!!
            echo "<script type='text/javascript'>
                         alert('Don\'t have a record');
                    </script>";

            $code= $_GET['unit_code'];
            $name= $_GET['unit_name'];
            $lecturer= $_GET['lecturer'];
            $semester= $_GET['semester'];

            $query = "INSERT INTO units (`unit_code`,`unit_name`,`lecturer`,`semester`) VALUES ('$code','$name','$lecturer','$semester');";
            $mysqli->query($query);
    ?>
评论
WOW
WOW

您正在使用Ajax请求URL。

The data variable will have a chunk of HTML, including the script element, in it.

You aren't doing anything with the value of data. You're just ignoring it.

通常,在处理Ajax时,您将以JSON之类的格式而不是HTML返回原始数据。然后,您可以使用客户端代码进行处理。

例如

header("Content-Type: application/json");
if (1) { # Use a real condition here
    echo json_encode([ "error" => "Don't have a record" ]);
    exit;
} else {
    # do database stuff and then…
    echo json_encode([ "success" => "Something something" ]);
    exit;
}

随着:

$.get("tute7_add.php", {
  unit_code,
  unit_name,
  lecturer,
  semester,
}).done(function (data) {
  if (done.success) {
    alert("You have added a unit successfully!");
  } else {
    alert(done.error);
  }
});
点赞
评论