JQuery异步请求PHP--POST请求

版权声明:撰写不易,转载请注明原文出处,如有错误,欢迎批评指正。如有版权问题,请联系[email protected] https://blog.csdn.net/qq_42195688/article/details/80373161

comment.php

<?php
// 测试$.post()方法
// echo json_encode($_POST);


if(!empty($_POST)){
    echo json_encode($_POST);
    die;
}
$data = array("name" => "测试者", "comment" => "这是测试内容");
echo json_encode($data);

index.html--这里用到了jquery,需要自行下载进行引入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>jquery-ajax发送post请求</title>
</head>
<body>

<div>Ajax无刷新评论</div>
<ul>
    <li>姓名:<input type="text" id="input_name" /></li>
    <li>评论:<input type="text" id="input_comment" /></li>
</ul>
<input type="button" value="发表评论" />
<table border="1"></table>

<script src="./jquery.min.js"></script>
<script>
// 1.使用$.post()方法发送post请求,与$.get()用法相同
// $(function(){
//     $.post("./comment.php", {name:'tom',age:23}, function(msg){
//         alert(msg.name + " " + msg.age);
//     }, "json");
// });

// 2.使用全局ajax参数发送post请求
$(function(){
    // 设置全局ajax
    $.ajaxSetup({
        url:"./comment.php",
        type:"POST",
        dataType:"json",
        success:comment_add
    });
    // 添加按钮单击事件
    $(":button").click(comment_send);
    // 获得默认数据
    $.ajax();
});

function comment_send(){
    var name = $("#input_name").val();
    var comment = $("#input_comment").val();
    // 提交与获取数据
    $.ajax({data:{name:name,comment:comment}});
}

function comment_add(data){
    html = "<tr><td>" + data.name + "</td><td>" + data.comment + "</td></tr>";
    $("table").append(html);
}
</script>
</body>
</html>

原文地址:https://blog.csdn.net/qq_42195688/article/details/80373161

猜你喜欢

转载自blog.csdn.net/qq_42195688/article/details/80373161
今日推荐