AJAX数据类型JSON和HTML

时间:2016-02-22 11:46:47

标签: php jquery json ajax

我正在关注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更好?

1 个答案:

答案 0 :(得分:2)

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 - 是基于意见或基于案例的问题。