JSON编码无法在Ajax函数中正常工作

abi*_* er 1 javascript php ajax jquery json

我建立了一个事件来更改与ajax和json编码混合的产品名称

<div class="new-product-name"></div>
 <div class="new-product-num"></div>
Run Code Online (Sandbox Code Playgroud)

然后脚本是

$(function(){
  $.ajax({
    method: "POST",
    url: "fetch-product.php",
    data: {keyword: 12}
  }).done(function(msg){
    $(".new-product-name").html(msg);

    $.getJSON("fetch-product.php", function(data) {
      $(".new-product-name").html(data.a);
      $(".new-product-num").html(data.b);         
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

fetch-product.php中

$query = "SELECT * FROM `product_details` WHERE id='". $_POST['keyword']."'";
$result = $conn->query($query);

if ($result->num_rows > 0) {
  $row = $result->fetch_assoc(); 
  $name=$row["p_name"];
  $num=$row["num"];
}

echo json_encode(array("a" =>  $name, $num));
Run Code Online (Sandbox Code Playgroud)

这里的产品详细信息正在正确提取中,即使$(".new-product-name").html(msg);显示出来'{"a":"Product1", "b":"22"}',也正在进入 $.getJSON("fetch-product.php", function(data) { }

但是data.adata.b显示出来null

为什么data.adata.b null?我花了太多的时间。请帮助解决此错误。

Rig*_*lly 5

我认为没有理由对PHP脚本进行2次调用。

如果您添加dataType:json参数,jQuery将期望PHP返回一个JSONString msg并将其自动转换为javascript对象。

$(function(){
    $.ajax({
        method: "POST",
        dataType: "json",         // new param
        url: "fetch-product.php",
        data: {keyword: 12}
    })
    .done(function(msg){
        if ( msg.status == 1 ) {
            $(".new-product-name").html(msg.a);
            $(".new-product-num").html(msg.b); 
        } else {
             $(".new-product-name").html(msg.info);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

调用的另一个问题$.getJSON("fetch-product.php",.....是,这将发出GET请求,因此将$_GET所有参数填充到数组中。您的PHP代码不在寻找在$_GET数组中传递的参数!

您的PHP代码实际上很容易受到SQL注入的攻击,因此我对其进行了修改,以使用Parameterized&Prepared语句。

您还需要考虑查询未找到任何内容的可能性,并返回一些信息让javascript知道。

$query = "SELECT * FROM `product_details` WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_POST['keyword']);
$result = $stmt->execute();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc(); 
    echo json_encode(array( 'status'=> 1,
                            'a'=>$row["p_name"], 
                            'b'=>$row["num"]);
} else {
    echo json_encode(array('status'=>0,
                            'info'=>'No data found');
}
Run Code Online (Sandbox Code Playgroud)