包子

木森技术分享

路漫漫其修远兮,吾将上下而求索。

您现在的位置是:网站首页 > THINKPHP

thinkphp5使用AJAX的几个坑

2021-03-13 18:45:53253

  1、success回调方法的data需要处理一下,否则返回的是 object object

$("#content").append(JSON.stringify(data));

  2、success回调方法中append,需要将button的type设置为button,否则会造成append的数据一闪而过

  原因应该是button的type默认为submit或者reset,导致提交后自动刷新页面

<button type="button" onClick="ajaxPost()">-----提交-----</button>

  3、第2点提到了设置button的type之后,append可以持久化,但是新数据会一直追加

  需要在append前加一句,这样每次点击都会清空内容

$("#content").empty();//事先清空下内容,注意empty remove detach的区别

  4、取消checkbox选中状态

$(":checkbox").prop("checked",false);// 设置checkbox选中状态,true设为选中 false设为取消

  5、给button设置一个disabled属性,防止用户多次点击

$("button").attr("disabled",true);//防止重复提交,将按钮设置为disabled

  success方法完整代码如下:

success: function (data) {
    $("#content").empty();//事先清空下内容,注意empty remove detach的区别
    $("#content").append(JSON.stringify(data));//获取成功以后输出返回值
    $(":checkbox").prop("checked",false);// 设置checkbox选中状态,true设为选中 false设为取消
    $("button").attr("disabled",true);//防止重复提交,将按钮设置为disabled
    // alert(JSON.stringify(data));
},