AJAX通过jQuery登录API

时间:2011-10-20 16:01:05

标签: jquery ajax

我正在尝试使用AJAX / jQuery为API设置登录表单。

在终端中,当我跑: $ curl -d'mail="me@gmail.com&密码= 123123'https://api.xyzcompany.com/users/login.json

它返回API令牌和Auth ID的哈希值: { “的auth_token”: “23049asfd0990235”, “AUTH_ID”: “2304990”}

这是我到目前为止所拥有的:

    <form id="loginForm" action="login_submit" method="get" accept-charset="utf-8">
        <fieldset>
            <div data-role="fieldcontain">
                <label for="email">Email</label>
                <input type="text" name="email" id="email" value=""  />
            </div>

            <div data-role="fieldcontain">
                <label for="password">Password</label>
                <input type="password" name="password" id="password" value=""  />
            </div>

            <button type="submit" data-theme="g" name="submit" >Login</button>

        </fieldset>
    </form>

</div><!-- /page -->

$("#loginForm").submit(function(event)
{
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "https://api.xyzcompany.com/users/login.json",
        data:({
            email : $('#email').val(),
            password: $('#password').val()
        }),
        success: function(result)
        {
            if(result=='ok')
            {
                window.location = 'http://www.google.com/'; //just to show that it went through
            }
            else
            {
                $('#result').empty().addClass('error')
                    .append('Something is wrong.');
            }
        }
    });
    return false;
}

正如您可能猜到的,当我点击提交时,没有任何反应。我非常感谢任何帮助将“curl -d”命令转换为有效的AJAX调用。谢谢!

1 个答案:

答案 0 :(得分:0)

$("#loginForm").submit(function(event)
{
    event.preventDefault();
    $.ajax({
        type: "GET",
        datatype:"json",
        url: "https://api.xyzcompany.com/users/login.json",
        data:({
            email : $('#email').val(),
            password: $('#password').val()
        }),
        success: function(result)
        {
            if(result && result.auth_token.length>1) // you should do your checking here
            {
                window.location = 'http://www.google.com/'; //just to show that it went through
            }
            else
            {
                $('#result').empty().addClass('error')
                    .append('Something is wrong.');
            }
        }
    });
    return false;
}