javascript - 这个post提交方式哪里写的不对呢?

查看:116
本文介绍了javascript - 这个post提交方式哪里写的不对呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

提交后插入不了数据 是我ajax写的不对吧?
tt.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function ajax(url,data,funsucc){
            var oAjax=new XMLHttpRequest();
            oAjax.open('POST',url,true);                   
            oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            oAjax.send("aa="+data);    
            oAjax.onreadystatechange=function(){
              if(oAjax.readyState==4){
                if(oAjax.status==200){
                  funsucc(oAjax.responseText);
                }
             }
           }
        }
    </script>
    <script type="text/javascript">
        window.onload=function(){
            var oTxt=document.getElementById('txt1');
            var oBtn=document.getElementById('btn1');
            oBtn.onclick=function(){
                ajax("ajax.php",oTxt.value,function(){
                    window.location.reload();
                });
            }
        }
    </script>
</head>
<body>
<form method="post">
    <input type="text" id="txt1">
    <button id="btn1" type="submit">提交</button>
</form>
</body>
</html>

ajax.php

<?php
$pdo=new PDO("mysql:host=localhost;dbname=t1","root","");
$txt=$_POST["aa"];      
$stmt=$pdo->prepare("insert into ajax(txt)values(?)");
$stmt->execute(array($txt));
?>

解决方案

1、提交按钮点击默认会触发onsubmit事件,而你给它绑定的onclick事件里没有取消默认事件;

oBtn.onclick=function(e){
    var e=window.event||e;
    e.preventDefault&&e.preventDefault();
    e.returnValue&&e.returnValue=false;
}

2、采用默认onsubmit,无视ajax,txt1加上name="aa";

这篇关于javascript - 这个post提交方式哪里写的不对呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆