var newusername = $(this).val(); 只发出按钮的值

mac*_*kee 0 javascript php jquery

继承了我的问题,当我试图将我的数据发送到PHP时,它只发送<button>或的值<input type="button">.

如果我删除了变量的定义,它只会将数据作为字符串发送,如果我有这样的话

newusername: "newusername",
newpassword: "newpassword",
newclub: "newclub"
Run Code Online (Sandbox Code Playgroud)

如果我删除了""我将在jquery.mini.js中得到一个错误

HTML:

<form method="post">
    <div class="form-group">
        <label> Username </label>
        <input type="text" class="form-control" id="newusername">
    </div>
    <div class="form-group">
        <label> Password </label>
        <input type="password" class="form-control" id="newpassword">
    </div>
    <div class="form-group">
        <label> Your club </label>
        <input type="text" class="form-control" id="newclub">
    </div>
    <input type="button" id="btn-reg">
</form>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

console.log('Script loaded...');

$("#btn-reg").on("click", reg);      

function reg(newusername, newpassword, newclub) {
    console.log('Klick, klick...');
    var newusername = $(this).val();
    var newpassword = $(this).val();
    var newclub = $(this).val();

    $.post('classCalling.php', {
        newusername: "newusername",
        newpassword: "newpassword",
        newclub: "newclub"
    },
    function(data){
        console.log(data);
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我看到两件事:

  • 发送的对象的定义很糟糕.该对象由键值对组成,您将其设置为硬编码的字符串值.

  • 开头的变量捕获$(this).val()都是一样的.您没有将其作为DOM对象获取.您应该在括号中进行CSS查询(即$("---this--")).


function reg(newusername, newpassword, newclub) {

    console.log('Klick, klick...');

    // if there is a input with class newusernameand only one
    var newusername = $('input.newusername').val();

    //if there is a input with class newpassword and only one
    var newpassword = $('input.newpassword').val();

    //if there is a input with class newclub and only one
    var newclub = $('input.newclub').val();

    $.post('classCalling.php',
        {
            newusername: newusername,
            newpassword: newpassword,
            newclub: newclub
        },
        function(data) {
            console.log(data);
        });
}
Run Code Online (Sandbox Code Playgroud)