Ajax变量在php中不起作用

Ajax variable not working in php

本文关键字:不起作用 php 变量 Ajax      更新时间:2023-09-26

这里我通过JavaScript从HTML页面获取值,从ajax访问该值,并将该值传递给PHP页面。

PHP页面应该使用该ajax值从表中删除,但PHP没有获得该ajax值。。。

以下是我尝试过的:

JavaScript

var str;
function getResults(a) 
{
       str = a;
}
function showUser() {
    if(str=="") {
        document.getElementById("txtHint").innerHTML="";
        return;
    }
    if(window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","getmovie.php?q="+str,true);
    alert(str);
    xmlhttp.send();
}

PHP

<?php
$q = strtolower(trim($_GET["q"]));
try 
{
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
}
catch (PDOException $e) 
{
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
$sth->execute();
$dbh = null;
?>

这,代码看起来很好,尝试在delete operation之后使用echo,如

    .......
    ......
    if(!$q)  {// check the movie name,  if empty then return;
       echo 'Movie name is empty';
       return;
    }
    $sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
    $sth = $dbh->prepare($sql);
    $sth->bindValue(':q', $q);
    if($sth->execute())  $msg=$q.' deleted successfully.';
    else $msg=$q.' not deleted.';
    $dbh = null;
    echo $msg;
    return;
?>

您是否将Rohan给您的代码放在catch子句之后

$q = strtolower(trim($_GET["q"]));
$q = strtolower(trim($_GET["q"]));
try 
{
$dbh = new PDO('mysql:dbname=your_database;host=localhost','your_user','your_password');
}
catch (PDOException $e) 
{
echo 'Connection failed: ' . $e->getMessage();
}
if(!$q)  {// check the movie name,  if empty then return;
   echo 'Movie name is empty';
   return;
}
$sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
if($sth->execute())  $msg=$q.' deleted successfully.';
else $msg=$q.' not deleted.';
$dbh = null;
echo $msg;
return;
?>