3

我正在尝试使用以下 jQuery 代码在以下 HTML 中查找用户 ID 和密码的值,但它不返回任何值。我究竟做错了什么?

<div id='mainpane'>
    <form id='login' method='post' action='#'>
        <p>User Id:<input id='userid' type='text' name='userid'></input></p>
        <p>Password:<input id='password' type='text' name='password'></input></p>
        <p><input id='submit' type='submit' name='Submit' value='Submit'></input></p>           
    </form>
    <div id="message"></div>
    <p>Not a member? <a href="user-signup.html">Signup</a></p>
</div>

这是jQuery代码:

$(document).ready(function() {
    $('#login').delegate('input#submit','click',function(){
        alert('user id is: '+$(this).parent().parent().find('#userid').html());
        var request = $.ajax({
            type:"POST",
            url:"/login",
            data: {userid:$('#userid').text(), password:$('#password').text}
            });

        });

警报返回一个空数据。感谢任何关于我做错了什么的指示。

谢谢,卡利安。

4

4 回答 4

4

用于.val()检索输入的值。

var userid = $("#userid").val();
var pass   = $("#password").val();
于 2012-05-24T03:32:41.380 回答
2

做就是了:

$.post('/login', $('#login').serialize(), function() {});

代替您的$.ajax电话:),.serialize()获取所有表单输入的值并将它们传递给服务器,并为您编码:)

于 2012-05-24T03:32:51.317 回答
2

你有很多问题,所以这里是带有注释的更正代码:

jQuery

$(function() {
// same as document.ready
    $('#login').submit(function(event){            
    // runs whenever the form is submitted - either enter or submit button is clicked
        event.PreventDefault();
        // since the form is submitted via ajax you wil want to keep the page from changing
        alert('user id is: '+$('#userid').val());
        // no need to reach back through the DOM with .parent() use the ID its the fastest, also you get input values with .val()
        $.ajax({
            type:"POST",
            url:"/login",
            data: $('#login').serialize()
            // serialize() creates an object of all the form data based on the name attribute and values - very clean
        });
    });
});

HTML

<div id='mainpane'>
    <form id='login' method='post' action=''>
        <p>User Id:<input id='userid' type='text' name='userid'/></p>
        <p>Password:<input id='password' type='text' name='password'/></p>
        <p><input id='submit' type='submit' name='Submit' value='Submit'/></p>           
    </form>
    <div id="message"></div>
    <p>Not a member? <a href="user-signup.html">Signup</a></p>
</div>

输入是自闭合的。

于 2012-05-24T03:36:32.050 回答
-1

你试试这个代码

 $(document).ready(function() {
        $('#login').delegate('input#submit','click',function(){

            alert('user id is: '+$(this).parent().parent().find('#userid').val());
            var request = $.ajax({
                type:"POST",
                url:"/login",
                data: {userid:$('#userid').val(), password:$('#password').val()}
                });

            });
        });
于 2012-05-24T03:38:48.337 回答