问题描述
我正在使用AJAX并尝试返回在查询modcomp.php文件中的数据库后获得的变量,然后尝试将这些值重新输入到我的主站点中以放入输入框.以下是我尝试过的方法,但无法正常工作.这是因为我要在PHP中获取变量,然后将其重新用于JS/jQuery中?进行一些看起来像JSON的搜索可能是答案,但是看着JSON,我还没有看到一个示例,该示例如何运行代码来查询数据库,然后将该信息转换为JSON格式以进行回退?我的目标是最终撤回所有10个变量.
I am using AJAX and trying to return variables that I got after querying the database in the modcomp.php file, I am then trying to input those values back into my main site to put into input boxes. Below is what I have tried but it is not working. Is this because I am getting variables in PHP and then bringing them back to use in JS / jQuery? Doing a few searches it looks like JSON might be the answer but looking at JSON I havent seen an example of how I could run code to query the database and then put that info in JSON format to pull back? My goal is to eventually pull back all 10 variables.
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val($itemnumber);
$('#cost').val($cost);
}
});
modcomp.php文件
The modcomp.php file
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$id=$row[0];
$itemnumber=$row[1];
$itemname=$row[2];
$cost=$row[3];
$company=$row[4];
$contact=$row[5];
$address1=$row[6];
$address2=$row[7];
$phone=$row[8];
$part=$row[9];
//print_r ($id." ".$itemnumber." ".$itemname." ".$cost." ".$company." ".$contact." ".$address1." ".$address2." ".$phone." ".$part);
} else {
print_r("Issue with query");
}
}
?>
推荐答案
最简单的方法是将jquery.ajax设置为期望json作为返回值:
The easiest way to do that is just set your jquery.ajax to expect a json as return:
$.ajax({
method: "POST",
dataType: "JSON",
/** others attributes **/
之后,将您的返回值转换为json并在php脚本中将其打印(仅此而已,仅此而已):
After, convert your return to a json and print it (just it, nothing more) at php script:
//a better approach is return the column name (fetch_assoc)
echo json_encode($row);
现在,您的回报可以用作json:
Now, your return can be used as json:
success: function(data) {
data.column_name
}
这篇关于从AJAX/php文件返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!