php - $.ajax 查询未发布到 PHP

标签 php jquery mysql ajax

我今天大部分时间都在尝试将 jQuery 变量发送到我的 PHP 文件并在 SQL 搜索中使用它。我的第一个问题是,甚至无法正确地将变量输入 PHP。我还收到了有关我也包含的一些 SQL 代码的错误。

我想要的:jQuery 中名为 name 的变量发送到 PHP 文件,在 SQL 查询中使用它来查找音乐家的真实姓名。然后,真实姓名将被发送回 HTML 文件,并在网页上显示。 MyPHPAdmin 和我的数据库已经设置完毕。

jQuery:

$('li').click(function () {
    var name = $(this).text(); 

    $('#prf').attr("class",name);
    $('#pic').attr("class",name);
    $('#info').attr("class",name);
    JSON.stringify (name);
     $.ajax({
    type: "POST",
    url: "ajax-name.php",
    data: {name: name}
            })

PHP:

$rname = $_POST['name']; 
var_dump($rname); 
try {
    $db = new PDO('mysql:dbname=dbname;host=myhost;charset=utf8', 'user', 'pass');

    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query="SELECT realname FROM artistmaster WHERE stagename = :name";
            $stmt = $db->prepare($query);
            $stmt->execute(array("name"=>$rname));    
        var_dump($rname);
        echo 'Success';            
        $result=$stmt->fetchAll();
            print "<pre>";
            print_r($result);
            print "</pre>";         
        }

        catch(PDOExeception $e)
        {
            echo $e->getMessage();
        }

输出:

NULL NULL 

我已阅读有关 $.ajax() 的文档,但仍然无法弄清楚我做错了什么。我很感谢对此的任何帮助,这让我度过了一段痛苦的时光。

最佳答案

要评估来自 AJAX 请求的 PHP 脚本的输出,请向您的请求添加返回处理程序:

$.ajax({
    type: "POST",
    url: "ajax-name.php",
    data: {name: name}
            }).always(function( html ) {
    console.log(html); // this will show the content of the php script in the developer console of your browser
  });

每次 AJAX 请求完成时都会调用 .always() 中定义的函数。当您确保您的代码可以工作时,您可以将其更改为 .done(),它仅在 AJAX 调用成功时调用。您还可以添加 .failure() 函数来优雅地处理错误。

另请注意 from the documentation :

The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use.

我建议改用 $.post 函数:

$.post("ajax-name.php", {name: name}, function( html ) {
    $('#outputdiv').html(html);
    // this will replace the content of a <div id="outputdiv"></div> with the output of the AJAX request
});

关于php - $.ajax 查询未发布到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24198330/

相关文章:

php - 如何在 PHP 页面上显示 hg 存储库的当前工作副本版本

javascript - 使用 jQuery 将页面顶部设置为距顶部 340px

mysql - 多表删除

Mysql删除外键时删除所有记录

php - cURL 需要 CURLOPT_SSL_VERIFYPEER=FALSE

php - Laravel 多通知类型

javascript - jQuery ajax : how to destroy submit if ajax validation fails?

javascript - 当接近页面底部时添加/删除类

php - 如何创建在个人电脑上运行的私有(private)网络服务器

php - sphinx表在其他基础上查表