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

标签 javascript php jquery

这是我的问题,当我尝试将数据发送到 PHP 时,它只发送 <button> 的值或<input type="button"> .

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

newusername: "newusername",
newpassword: "newpassword",
newclub: "newclub"

如果我删除 ""我会在 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>

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);
    });
}

最佳答案

我看到两件事:

  • 发送的对象的定义是错误的。该对象由键值对组成,您将这些键值对设置为硬编码的字符串值。

  • 开头$(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);
        });
}

关于javascript - var newusername=$(this).val();只发送按钮的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728699/

相关文章:

PHP PDO - MySQL 查询创建或更新(唯一索引)

php - 使用 PHP、AJAX 和 JavaScript 的简单按钮点击计数器

php - 流明自动增量关系创建保持在 0

php - 从 jquery 中的对象获取结果

javascript - 如何在 Bower 中注册本地 git 包?

javascript - 带有 Flask 服务器的 d3 饼图

javascript - 在 aspx 页面中自动运行 javascript 函数

javascript - WebSQL : Are returned rows in SQLResultSetRowList immutable?

javascript - 如何在 jQuery datetimepicker 中添加 12 小时格式?

javascript - HTML5 视频尺寸