Как сделать авторизацию при помощи Jquery и Json - PullRequest
0 голосов
/ 31 марта 2011

У меня есть сервер, который, если я сделаю вызов, вернет файлы json.В основном у меня есть несколько пользователей, которые могут быть вызваны.

ex: http://server.insource.local/users/145
ex: http://server.insource.local/users/146
ex: http://server.insource.local/users/147

Что я хочу сделать, чтобы каким-то образом отправить имя пользователя и пароль на сервер, если правильно, отправьте обратно одну из тех ссылок, которые соответствуют этому имени пользователяи пароль.

Идея не в том, чтобы использовать какой-либо php.

Я возьму что-нибудь, любую идею, любой пример.

пример скрипта на стороне обслуживания?спасибо

edit: я выяснил, что путь ссылки - это то, что возвращает мою информацию, и что сервер все равно запрашивает аутентификацию, так что я просто проверяю их друг против друга

спасиборебята

Ответы [ 3 ]

3 голосов
/ 31 марта 2011

Вы можете рассмотреть AJAX вызов с jQuery .

Вот пример кода:

$.ajax
    ({
        type: "POST",
        //the url where you want to sent the userName and password to
        url: "http://your-url.com/secure/authenticate.php",
        dataType: 'json',
        async: false,
        //json object to sent to the authentication url
        data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
        success: function (){
            //do any process for successful authentication here
        }
    });

Конечно, сначала вам нужно будет ввести введенное пользователем значение из полей userName и password .

На стороне сервера вы можете выполнить всю проверку и отправить простое сообщение, такое как authenticated или failed . success часть вызова ajax предназначена для выполнения любого процесса после аутентификации пользователя.

Подробнее о jQuery AJAX http://api.jquery.com/jQuery.ajax/

** ОБНОВЛЕНИЕ **

Скажем, у вас есть этот HTML-код:

<input type="text" name="username" id="username" class="text" maxlength="30" />
<br />
<input type="password" name="password" id="password" class="text" maxlength="30" />
<br />
<input type="submit" name="btnSubmit" id="btnSubmit" />

Вы можете использовать этот скрипт jQuery для сбора ввода пользователя и выполнения вызова ajax:

    $(document).ready(function () {
        //event handler for submit button
        $("#btnSubmit").click(function () {
            //collect userName and password entered by users
            var userName = $("#username").val();
            var password = $("#password").val();

            //call the authenticate function
            authenticate(userName, password);
        });
    });

    //authenticate function to make ajax call
    function authenticate(userName, password) {
        $.ajax
        ({
            type: "POST",
            //the url where you want to sent the userName and password to
            url: "http://your-url.com/secure/authenticate.php",
            dataType: 'json',
            async: false,
            //json object to sent to the authentication url
            data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
            success: function () {
                //do any process for successful authentication here
            }
        })
    }
0 голосов
/ 22 марта 2013
$.ajax
({
    type: "POST",
    //the url where you want to sent the userName and password to
    url: "http://your-url.com/secure/authenticate.php",
    dataType: 'json',
    async: false,
    //json object to sent to the authentication url
    data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
    success: function (){
        //do any process for successful authentication here
    }
});
0 голосов
/ 13 марта 2013

Проверьте следующий код:

$.ajax
({
    type: "POST",
    //the url where you want to sent the userName and password to
    url: "http://your-url.com/secure/authenticate.php",
    dataType: 'json',
    async: false,
    //json object to sent to the authentication url
    data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
    success: function (){
        //do any process for successful authentication here
    }
});
...