AJAX 数据类型 JSON 和 HTML


AJAX datatype JSON and HTML

我正在遵循有关ajax的教程,并制作了这个脚本,其中我以JSON形式获取数据并将它们附加到表中:

$.ajax({
    url: 'insert.php', 
    type: 'POST', 
    data: {data1: name, data2: phone, data3: address},
    dataType: "json", 
    success:function(res){
        //if(data=="success")
        //{
            //alert("Data added");
            //console.log(arr.id);
            $("#trId").before("<tr><td>"+res.emp_name+"</td><td>"+res.ph+"</td><td>"+res.add+"</td></tr>");
        //}
    },
    error:function(res){
        alert("data not added");
    }

这是PHP代码:

$insert = "INSERT into employee(emp_name, phone, address) VALUES (:emp_name, :ph, :add)";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":emp_name", $emp_name);
$insertStmt->bindValue(":ph", $pos);
$insertStmt->bindValue(":add", $address);
$insertStmt->execute();
//echo "success";
$lastid = $conn->lastInsertId();
$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo json_encode($res);

我们的讲师要求我们将此脚本从作为数据类型的 JSON 转换为 HTML,并对其进行初始更改。但是我不知道 PHP 代码现在应该返回什么,以及如何将返回的值附加到表中。

其次,为什么有些人使用HTML作为数据类型,而JSON更好?

dataType设置为 html:

dataType: "html"

并在服务器上呈现 html:

$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo "<tr><td>" . $res['name'] . "</td><td>" . $res['ph'] . "</td><td>" . $res['add'] . "</td></tr>"";

因此,在success回调中,您将收到html

success: function(res) {
    $("#trId").before( res );
}

为什么使用html而不是json - 是基于意见或基于案例的问题。