ajax在button中使用onclick失效原因

        在做页面提交的时候,发现通过button中onclick绑定的方法时,怎么也无法提交ajax请求,但是使用click方法的时候确实可以成功。因缺思厅。这里做下分析。先看下代码

1、使用onclick方法

<input id="login" name="" οnclick="login()" type="button" class="btn btn-success radius size-L col-xs-3" value=" 登    录 ">
function login() {
        $.ajax({
            type:"POST",
            url:"{:url('admin/login/check')}",
            data:$("form").serialize(),
            dataType:'json',
            success: function(data) {
                    if (data.status == 1) {
                        window.location.href="{:url('index/index')}";
                    }else {
                        alert(data.message);
                    }
            }
        });
    }

2、使用click方法

$(function(){
        $("#login").on('click',function (event) {
            $.ajax({
                type:"POST",
                url:"{:url('admin/login/check')}",
                data:$("form").serialize(),
                dataType:'json',
                success: function(data) {
                    if (data.status == 1) {
                        window.location.href="{:url('index/index')}";
                    }else {
                        alert(data.message);
                    }
                }
            });
        })
    })

分析

    查阅资料后,明白ajax动态加载之前js就加载完了。这TM就很尴尬了,使用onclick没有绑定上,而第二种方法之所以可以成功,主要是因为$(function(){})的原因,简单的来说,这个函数可以在文档载入完成后执行,就是因为这个原因,所以第二个方法提交ajax才可以成功!


发布了15 篇原创文章 · 获赞 13 · 访问量 3万+
展开阅读全文

click事件的ajax触发不了,请求大神解答

06-20

``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录</title> <link rel="icon" href="/assets/images/favicon.ico?verson=<%=Math.random()%>>"> <link href="/assets/css/base1.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/base.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/global.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .login_fs { position: absolute; right: 0; top: 9.5%; width: 52px; height: 52px; cursor: pointer; z-index:100 } .qrcode_btn { background: #ffffff url(/assets/images/loginfs.png) no-repeat; } .qrcode_btn:hover { background: #ffffff url(/assets/images/loginfs.png) no-repeat 0px -60px; } </style> <script type="text/javascript" src="/assets/js/jquery.min.js"></script> <script type="text/javascript" src="/assets/js/jquery-ui.min.js"></script> <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script> </head> <body class="login_bg"> <div class="logo"><div class="fl"><img src="/assets/images/logo.png?verson=<%=Math.random()%>>"/></div><div class="fl logolm">办公系统</div></div> <div class="login"> <div class="login_fs qrcode_btn" title="微信扫码登录" onclick="showQrcode()"></div> <div id="login"> <form action="/login" method="post" id="myform" class="form-horizontal" > <div class="login_tab"> <div class="lm">员工登录</div> <div class="login_form"> <ul> <li class="login_user"><input id="userName" name="staffVO.userName" type="text" style="width:95%" class="login_text" value="" placeholder="登录用户名" required autofocus /></li> <li class="login_pass"><input id="password" name="staffVO.password" type="password" style="width:95%" class="login_text" placeholder="登录密码" required/><span class="error">${errorMessage }</span></li> <li class="login_btndiv" style="margin-top: 25px"><input id="Button1" type="submit" value="登录" class="login_btn"/></li> </ul> </div> <div class="mt10"><a href="/toResetStep1" style="color:#ee5252" >忘记密码/花名</a></div> <div class="mt10">地区:通州,南通,如东,广州,南京,佛山</div> </div> </form> <div class="login_banner">创新  专业  合作  务实</div> </div> </div> <div id="loginTab" style="position:absolute;top:20%;left:38%;display:none"></div> <script type="text/javascript"> $(function(){ var code = '${param.code}'; if(code){ location.href = "/index"+location.search; } }); var appID = "wx9c2800cfc46895f0"; var uri = "http://www.zhizaolian.com:9090"; var obj = new WxLogin({ id: "loginTab", appid: appID, scope: "snsapi_login", redirect_uri: encodeURI(uri), state: guid() }); function showQrcode(){ $(".login").css("opacity", "0.1"); $(".logo").css("opacity", "0.1"); $("#loginTab").css("display", "block"); $("input").css("pointer-events", "none"); $(".qrcode_btn").css("pointer-events", "none"); } $("#login, .logo").click(function(){ if($("#loginTab").css("display")=='block'){ $("#loginTab").css("display", "none"); $(".login").css("opacity", "1"); $(".logo").css("opacity", "1"); $("input").css("pointer-events", ""); $(".qrcode_btn").css("pointer-events", ""); } }); function guid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } $("#Button1").click(function(){ alert(1); var userName =$("#userName").val(); var password =$("#password").val(); $.ajax({ url:'/chaxunContract', type:'post', data:{userName:userName,password:password}, dataType:'json', success:function(data){ alert(2); alert(data.diff); if(data.diff>3){ var params = $("#myform").serialize(); window.location.href="/login"+ decodeURICompoent(params,true); Load.Base.LoadingPic.FullScreenShow(null); }else if(data.diff<=3 && data.diff>=0){ layer.open({ offset:'100px', title:'提醒', content:"您的劳动合同于"+data.endDate+"到期,请联系人事部门进行续签", success:function(index){ layer.close(index); var params = $("#myform").serialize(); window.location.href="/login"+ decodeURICompoent(params,true); Load.Base.LoadingPic.FullScreenShow(null); } }) }else if(data.diff<0){ layer.alert("您的劳动合同已于"+data.endDate+"到期,请联系人事部门进行续签后再登录"); }else if(data.diff=='no'){ layer.alert("您暂时未签署劳动合同,请联系人事部门进行签署后再登录"); } } }) }) </script> </body> </html> ``` click事件的ajax触发不了,请求大神解答 问答

在jquery添加ajaxOnClick无法正常工作

01-31

<div class="post-text" itemprop="text"> <p>I have created a page, it has a select box which is used for filtering the results in a table below it. The select box is using ajax to filter results.The table which is loaded after ajax call has a button in one column, on its click a div should be added in the page. The onclick for this button was working fine when the table was static with static button to add div, now the table is being loaded through ajax the button doesn't work, it doesn't add the div that it was adding before. Can someone point out the problem please, I am a beginner in jquery and ajax </p> <p>here is my code:</p> <pre><code>(function ( $ ) { $(document).ready(function(){ var itemsArr = []; $(".btn-add").on("click",function() { var $row = $(this).closest("tr"); // Find the row var $text = $row.find(".this-name").text(); // Find the text // Let's test it out $('#col2').append('<div class="item"><p>'+$text+'</p><a href="#" class="delete-button">X</a></div>'); itemsArr.push($text); //alert(itemsArr); console.log("added"); $("#items").val(JSON.stringify(itemsArr)); }); function getAll(){ $.ajax ({ url: 'http://asp4.walnut-labs.com/getproducts.php', data: 'action=showAll', contentType :'application/json', cache: false, success: function(r) { $("#col1").html(r); } }); } getAll(); // function to get all records from table // code to get all records from table via select box $("#brands").change(function() { var id = $(this).find(":selected").val(); var dataString = 'action='+ id; $.ajax ({ url: 'http://asp4.walnut-labs.com/getproducts.php', data: dataString, contentType :'application/json', cache: false, success: function(r) { $("#col1").html(r); } }); }); }); $(document).on('click','.delete-button', function(e){ e.preventDefault(); //alert('yes'); $(this).closest('.item').remove(); }); }( jQuery )); </code></pre> <p>HTML is :</p> <pre><code><tbody> <tr bgcolor="#238efb" color="white"> <td style="text-align: center; color: #fff;"><strong>ID</strong></td> <td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Item Code</strong></td> <td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Item Name</strong></td> <td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Brand</strong></td> <td style="text-align: left; color: #fff; padding-left: 15px;"><strong>Button</strong></td> </tr> <?php while($row = mysql_fetch_array($comments, MYSQL_ASSOC)) { $id = $row['id']; $name = $row['code']; $level = $row['name']; $number = $row['brand']; ?><tr> <td class="this-id" style="text-align: center;"><?php echo $id;?></td> <td class="this-name" style="text-align: left; padding-left: 15px;"><?php echo $name;?></td> <td style="text-align: left; padding-left: 15px;"><?php echo $level;?></td> <td style="text-align: left; padding-left: 15px;"><?php echo $number;?></td> <td style="text-align: left; padding-left: 15px;"><button class="btn-add">Add Item</button></td> </tr><?php } mysql_close($con); ?> </tbody> </table> </code></pre> <p>For selectbox that triggers AJAX:</p> <pre><code><div class="searchbar"> <select name="brands" id="brands"> <option value="showAll" selected="selected">Show All Products</option> <?php $querybrand = "SELECT DISTINCT brand FROM q1h27_data "; $commentsbrand = mysql_query($querybrand); while($row = mysql_fetch_array($commentsbrand, MYSQL_ASSOC)) { //print_r($row['brand']);?> <option value="<?php echo $row['brand']; ?>"><?php echo $row['brand']; ?></option> <?php } ?> </select> </div> </code></pre> </div> 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览