dqcd84732 2016-02-22 11:46
浏览 113
已采纳

AJAX数据类型JSON和HTML

I am following a tutorial about ajax and I have made this script, where I get data as JSON and append them into a table:

$.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");
    }

And here is the PHP code:

$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);

Our instructor asked us to transform this script, from JSON as datatype into HTML, and make the initial changes for it. But I can't figure out what should the PHP code returns now, and how to append the returned values into the table.

Secondly, why some people use HTML as datatype while JSON is better ?

  • 写回答

1条回答 默认 最新

  • dongre1907 2016-02-22 11:53
    关注

    Set dataType to html:

    dataType: "html"
    

    And render html on server:

    $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>"";
    

    So in a success callback you will receive html:

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

    Why use html instead of json - is an opinion-based or a case-based question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码