简体   繁体   English

aJAX调用PHP文件

[英]aJAX call to PHP file

I have a need to use the $.ajax method to call a PHP file. 我需要使用$ .ajax方法来调用PHP文件。 I have to pass in a driver id to the PHP file, which then retrieves the id, executes a query to get the driver's name and return that name back to the form so I can autopopulate the appropriate textbox. 我必须将驱动程序ID传递给PHP文件,然后该PHP文件检索ID,执行查询以获取驱动程序的名称,并将该名称返回到表单,以便我可以自动填充适当的文本框。 Here is the ajax method: 这是ajax方法:

var id=$('#DriverID').val();
    $.ajax({
        url: 'drivername.php',
        data: {driverid: id},
        type: 'POST',
        success: function(data) {
            $.('#DriverName').val(data);
        }
    });

Here's the PHP: 这是PHP:

$driverid=$_POST['driverid'];


$host="Host to database";
$user="user"
$password="password";
$db="database";

$driver="";
$query="SELECT driver_name FROM drivers WHERE driver_id=$driverid";
$cn=mysqli_connect($host, $user, $password, $db);
$result=mysqli_query($cn, $query);
while($data=mysqli_fetch_array($result))
{
    $driver=$data['driver_name'];
}
echo $driver;

How do I configure the PHP file to return the driver's name, and also, is the ajax method syntax correct? 如何配置PHP文件以返回驱动程序的名称,而且ajax方法的语法正确吗?

It looks like your PHP script is already returning the "driver's name" variable that you're setting up with your SQL. 看起来您的PHP脚本已经在返回您使用SQL设置的“驱动程序名称”变量。 If your return value was larger or more complex (eg, multiple values, an array/object/etc), you could JSON encode it and use jQuery to JSON decode it. 如果您的返回值更大或更复杂(例如,多个值,数组/对象/等),则可以对其进行JSON编码,然后使用jQuery对其进行JSON解码。 To update CSS id "DriverName" with the return data, I think you just have an extraneous ".": 要使用返回数据更新CSS id“ DriverName”,我认为您只是有一个多余的“。”:

success: function(data) {
    $('#DriverName').val(data);
}

This question is quite similar: jQuery ajax - update div 这个问题非常相似: jQuery ajax-update div

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

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