简体   繁体   English

通过Ajax将PHP值返回给Javascript

[英]Returning PHP value to Javascript via Ajax

So I've been trying to return a value from a php script back to my javascript file but I cant figure it out. 因此,我一直试图从php脚本返回一个值回到我的javascript文件,但我无法弄清楚。 I know I'm supposed to use ajax but I'm not sure how that works. 我知道我应该使用Ajax,但是我不确定它是如何工作的。 My php file works fine. 我的php文件工作正常。 It searches a database and returns true or false if it finds that value. 它搜索数据库,如果找到该值,则返回true或false。 Now I want a variable in my javascript file equal to either true or false from the php file however I'm not sure how to set that variable equal to the php value. 现在,我希望我的javascript文件中的变量等于php文件中的true或false,但是我不确定如何将该变量设置为等于php值。 Can anyone help me out? 谁能帮我吗?

my php file: 我的php文件:

<?php

$username = "z";
$check;

$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "iarenadatabase";

$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);

if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno()) . ')' . mysqli_connect_error();
} else {

    $result = mysqli_query($conn, "SELECT * FROM iarenadbtable
WHERE Username LIKE '%{$username}%'");

    if ($result->num_rows) {
        $check = true;
        echo json_encode($check);
    } else {
        $check = false;
        echo json_encode($check);
    }

    $conn->close();
}

// header('Location: index.html');
exit;
?>

And what little I have of ajax. 而我对ajax的了解很少。 im not sure what to do with this. 林不知道该怎么办。

$('#test').click(function () {
  // alert("accessed");
  $.ajax({
    method: 'POST',
    url: 'DBSearch.php',
    data: "",

    dataType: 'json',
    success: function (data) {
      alert(data);
    }
  });
});

Im assuming 'data' should somehow end up equal to either true or false but im not sure how. 我认为“数据”应该以某种方式最终等于true或false,但不确定如何。

edit: nothing will print out within that success function whether I try and use data or just console.log("text"). 编辑:无论我尝试使用数据还是仅console.log(“ text”),在该成功函数中都不会输出任何内容。 It seems like that part isnt being accessed? 似乎该部分没有被访问?

if you mean you want in your javascript a boolean variable which represent $check variable in php. 如果您的意思是您想要在JavaScript中使用一个布尔变量,它表示php中的$ check变量。 then the data variable is already holding this value. 则数据变量已经保存了该值。

$check的值应该更像

{"success":"true"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM