Javascript Ajax-在PHP中使用Json时出错

Javascript Ajax-在PHP中使用Json时出错,javascript,php,mysql,json,ajax,Javascript,Php,Mysql,Json,Ajax,我正在尝试使用Ajax将JSON数据插入MySQL。 但我什么也没得到,查询不起作用 我什么都试过了,不知道问题出在Ajax、PHP还是JSON中 我应该从哪里开始寻找 JS代码 $("#btnprueba").click(function () { var array1 = []; $("#tabla .DataRow").each(function () { var firstTableData = {};

我正在尝试使用Ajax将JSON数据插入MySQL。 但我什么也没得到,查询不起作用

我什么都试过了,不知道问题出在Ajax、PHP还是JSON中

我应该从哪里开始寻找

JS代码

$("#btnprueba").click(function () {
            var array1 = [];
            $("#tabla .DataRow").each(function () {

                var firstTableData = {};
                var Aidi = $(this).find('td').eq(0).text().trim();
                    firstTableData.ID_Articulo = $(this).find('td').eq(0).text().trim();
                    firstTableData.Descripcion = $(this).find('td').eq(1).text().trim();
                    firstTableData.Valor_Venta = $(this).find('td').eq(2).text().trim();
                    firstTableData.Cantidad = $(this).find('td').eq(3).text().trim();
                    firstTableData.Subtotal = $(this).find('td').eq(4).text().trim();
                    array1.push(firstTableData);

            });

            var JsonValues = JSON.stringify(array1);
                alert(JsonValues);
            $.ajax({
                type: "POST",
                url: "GuardarDatosFactura2.php",
                data: "J="+JsonValues,
                success: function(response){
                    alert(response);
                },
                error: function(e){
                    console.log(e.message);
                },

            });

        });
变量JsonValues中的Json

[{"ID_Articulo":"001","Descripcion":"Caramelos","Valor_Venta":"6500","Cantidad":"2","Subtotal":"13000"}]
PHP代码

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

    $ID=$data->ID_Articulo;
    $Canti=$data->Cantidad;   
    $Vlr=$data->Valor_Venta;

    $cadena2 = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
    $create2 = mysqli_query($CON,$cadena2);

    if($cadena2){
        $MSG= "Se guardaron los datos";
    }
    else{
        $MSG= "No se guardaron los datos";
    }
    echo($MSG);



?>

您必须从json解码数据中获取数组值,如下所示:

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

    $ID=$data[0]->ID_Articulo;
    $Canti=$data[0]->Cantidad;   
    $Vlr=$data[0]->Valor_Venta;

    $cadena2 = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
    $create2 = mysqli_query($CON,$cadena2);

    if($cadena2){
        $MSG= "Se guardaron los datos";
    }
    else{
        $MSG= "No se guardaron los datos";
    }
    echo($MSG);



?>

您必须从json解码数据中获取数组值,如下所示:

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

    $ID=$data[0]->ID_Articulo;
    $Canti=$data[0]->Cantidad;   
    $Vlr=$data[0]->Valor_Venta;

    $cadena2 = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
    $create2 = mysqli_query($CON,$cadena2);

    if($cadena2){
        $MSG= "Se guardaron los datos";
    }
    else{
        $MSG= "No se guardaron los datos";
    }
    echo($MSG);



?>

这将帮助您在post请求中检查接收到的json上的I have loop,并使用for loop生成insert查询,以创建单个insert语句

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

$comma = "";
$query = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ";
foreach ($data as $key => $value) {
    $ID = mysqli_real_escape_string($CON, $value->ID_Articulo);
    $Canti = mysqli_real_escape_string($CON, $value->Cantidad);
    $Vlr = mysqli_real_escape_string($CON, $value->Valor_Venta);
    $query .= $comma . "('$ID','$Canti','$Vlr')";
    $comma = ",";
}

$create2 = mysqli_query($CON, $query);

if($cadena2){
    $MSG= "Se guardaron los datos";
}
else{
    $MSG= "No se guardaron los datos";
}
echo($MSG);
?>

这将帮助您在post请求中检查接收到的json上的I have loop,并使用for loop生成insert查询,以创建单个insert语句

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

$comma = "";
$query = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ";
foreach ($data as $key => $value) {
    $ID = mysqli_real_escape_string($CON, $value->ID_Articulo);
    $Canti = mysqli_real_escape_string($CON, $value->Cantidad);
    $Vlr = mysqli_real_escape_string($CON, $value->Valor_Venta);
    $query .= $comma . "('$ID','$Canti','$Vlr')";
    $comma = ",";
}

$create2 = mysqli_query($CON, $query);

if($cadena2){
    $MSG= "Se guardaron los datos";
}
else{
    $MSG= "No se guardaron los datos";
}
echo($MSG);
?>

Op,不要自己对数据进行json编码。让jQuery来处理这个问题。或者至少在对象中传递JSON编码的数据

您需要做的是将数据作为javascript对象传递给jQuery。通过这种方式,您可以让jQuery和PHP完成所有繁重的工作

     $.ajax({
            type: "POST",
            url: "GuardarDatosFactura2.php",
            data: {J: array1},
            //    ^^ Javascript object, passing the array as raw info.
            //    This way it will be passed as an object to your php.
            success: function(response){
                alert(response);
            },
            error: function(e){
                console.log(e.message);
            },

        });
然后在PHP中,您可以

$data = $_POST['J'];
PHP应该已经将其转换为本机PHP对象/数组

只需做一个
var\u转储($data);模具()以查看它已成为什么

如果对象嵌套得很深,php可能不会自动解码它。然后对其进行编码并传递编码的变量

data: {J: JSON.stringify(array1)},
在php中

$data = json_decode($_POST['J'], false);
注意,不是问,而是需要知道

您正在sql中使用未准备的变量

"INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
这是坏的。如果你的网站将成为正面的,那么任何人都可以转储你的数据库,读取你的数据库并破坏你的数据库,因为你让他们直接访问你的内部

请使用并且永远不要使用没有准备好的语句的查询。此外,您不计算重复的钥匙。如果产品已存在,则应更新,而不是重新插入

if ($stmt = $mysqli->prepare("INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES (?,?,?) ON DUPLICATE KEY UPDATE Cantidad=?, ValorVenta=?")) {
      $stmt->bind_param("i", $ID);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);

      mysqli_stmt_execute($stmt);
}

哦,不要自己对数据进行json编码。让jQuery来处理这个问题。或者至少在对象中传递JSON编码的数据

您需要做的是将数据作为javascript对象传递给jQuery。通过这种方式,您可以让jQuery和PHP完成所有繁重的工作

     $.ajax({
            type: "POST",
            url: "GuardarDatosFactura2.php",
            data: {J: array1},
            //    ^^ Javascript object, passing the array as raw info.
            //    This way it will be passed as an object to your php.
            success: function(response){
                alert(response);
            },
            error: function(e){
                console.log(e.message);
            },

        });
然后在PHP中,您可以

$data = $_POST['J'];
PHP应该已经将其转换为本机PHP对象/数组

只需做一个
var\u转储($data);模具()以查看它已成为什么

如果对象嵌套得很深,php可能不会自动解码它。然后对其进行编码并传递编码的变量

data: {J: JSON.stringify(array1)},
在php中

$data = json_decode($_POST['J'], false);
注意,不是问,而是需要知道

您正在sql中使用未准备的变量

"INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
这是坏的。如果你的网站将成为正面的,那么任何人都可以转储你的数据库,读取你的数据库并破坏你的数据库,因为你让他们直接访问你的内部

请使用并且永远不要使用没有准备好的语句的查询。此外,您不计算重复的钥匙。如果产品已存在,则应更新,而不是重新插入

if ($stmt = $mysqli->prepare("INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES (?,?,?) ON DUPLICATE KEY UPDATE Cantidad=?, ValorVenta=?")) {
      $stmt->bind_param("i", $ID);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);

      mysqli_stmt_execute($stmt);
}

您的PHP缺少开始标记。您还需要
使用bind和prepared语句。它将处理数据中的引号、转义字符,最重要的是,它是防止SQL注入的最佳防御措施。谢谢,我更正了以下问题:
$data
是关联数组的数组。要查看ajax调用的错误/响应。如果您使用的是Chrome浏览器,请按F12进入网络选项卡->XHR。在PHP文件中保留错误报告。您的PHP缺少开始标记。您还需要
使用bind和prepared语句。它将处理数据中的引号、转义字符,最重要的是,它是防止SQL注入的最佳防御措施。谢谢,我更正了以下问题:
$data
是关联数组的数组。要查看ajax调用的错误/响应。如果您使用的是Chrome浏览器,请按F12进入网络选项卡->XHR。在PHP文件中保留错误报告。我已经做了更改,但仍然没有工作:/能否打印
$data
数组并显示输出?您好,输出是:[object object],使用:echo json_encode($data);我已经做了更改,但仍然没有工作:/n您可以打印
$data
数组并显示输出吗?您好,输出是:[object object],使用:echo json_encode($data);