如何使用jQuery Ajax从PHP脚本获取JSON数据



我正在将数据插入表中,并在json中编码一些参数,我想显示它,但我很困惑。为什么我的json参数不显示?Console.log (result)显示json,但我想从json中显示单个参数,如Console.log (result.message);但是为什么会有误差呢?

脚本:

<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#form_id',function(e){
e.preventDefault();
var name= $("#name").val();
var quantity= $("#quantity").val();
var price=$("#price").val();

$.ajax({
type: "post",
url: 'insert.php',
data: {'name': name, 'quantity': quantity,'price':price},
success: function(result){

console.log(result.message);
console.log("success");
}
});
});
});

insert.php

<?php 
$servername="localhost";
$dbname="test";
$username="root";
$password="";
try{
$conn=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "success";
}
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
$name=$_POST['name'];
$quantity=$_POST['quantity'];
$price=$_POST['price'];

$sql="insert into product (product_name,product_quantity,product_price,barcode_image) values('$name','$quantity','$price','')";
$conn->exec($sql);
$data['message']="success";
$data['status']="ok";
echo json_encode($data);
?>

您应该在后端响应中设置您的content-type标头。(内容类型头)

添加header('Content-Type: application/json');echo行在您的php代码,或添加dataType: 'JSON'到您的ajax参数。(PHP头函数)

你应该关注@RiggsFolly关于sql注入的注释:

你的脚本是开放的SQL注入攻击。即使你在逃避输入,不安全!您应该始终使用准备好的参数化MYSQLI_或PDO API中的语句,而不是连接用户在查询中提供的值。永远不要相信任何用户输入!